Data binding in React can be achieved by using a controlled input
. A controlled input is achieved by binding the value to a state variable
and a onChange
event to change the state as the input value changes.
See the below snippet
class App extends React.Component {
constructor() {
super();
this.state = { value: 'Hello World' };
}
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
return (
<div>
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
<p>{this.state.value}</p>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>
_x000D_
Here is an equivalent function component of the class defined above.
const { useState } = React;
const App = () => {
const [value, setValue] = useState('Hello World');
const handleChange = (e) => setValue(e.target.value);
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>{value}</p>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
_x000D_