4 years ago
Zaid Bin Khalid
3,670 Views
2
In this session, we will learn how to use forms in React JS with example and code.
Simple Example
We will set an input form with value = {this.state.data} in the following example. Whenever the input value changes in the state this allows updating. With the help of the onChange event that will watch the input changes 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'));
When the input text value changes, the state value will be updated automatically.
Complex Example
We will see how to use forms from the child component, in the following example. The method which we used to target a state update that will be passed to the child input value and rendered on the display screen called the onChange method. In the Events, a chapter a similar example is used. Whenever we need to pass the function that will handle updating (update state ) as a prop (updateStateProp ), we need to update the state from the child component.
//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'));
we click the button, and we will get the following result.
4 years ago
Zaid Bin Khalid
3,670 Views
2