English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS Tables

In this chapter, we will learn how to use forms in React.

Simple example

In the following example, we will use the set input formvalue = {this.state.data}. As long as the input value changes, the state can be updated. We are usingonChangeEvent, which will monitor changes in input and update the state accordingly.

App.jsx

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState(e) {
      this.setState({data: e.target.value});
   }
   render() {
      return (
         <div>
            <input type = "text" value = {this.state.data} 
               onChange = {this.updateState} />
            <h4>{this.state.data}</h4>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/, document.getElementById('app'));

The state will be updated when the input text value changes.

Complex example

In the following example, we will see how to use the form in the child component.onChangemethod will trigger the state update, which will be passed to the child inputvalueand displayed on the screen. Similar examples are used in the Event chapter. Whenever we need to update the state from a child component, we must pass the handler for update (updateStateFunction as prop (updateStatePropPassing.

App.jsx

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState(e) {
      this.setState({data: e.target.value});
   }
   render() {
      return (
         <div>
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}/Content>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <input type = "text" value = {this.props.myDataProp} 
               onChange = {this.props.updateStateProp} />
            <h3>{this.props.myDataProp}</h3>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/, document.getElementById('app'));

This will produce the following result.