const [data, setData] = useState({
name: "",
});
const handleData = (name, value) => {
setData({
...data,
[name]: value,
});
};
onChange={(e) => handleData("name", e.target.value)}
return (
<input
type="text"
name="firstName"
onChange={ (event) => setName(event.target.value) }
value={name} />
)
import React, { Component } from 'react';
import './App.css';
import Header from './Header';
class App extends Component {
constructor(props) {
super(props);
this.state = {name: "Michael"}
}
changeTitle = (e) =>{
this.setState({name: e.target.value});
}
render() {
return (
<div className="App">
<Header title={this.state.name}/>
<p className="App-intro">
Type here to change name.
<input type="text" onChange={this.changeTitle}/>
</p>
</div>
);
}
}
export default App;
In React, onChange is used to handle user input in real-time.
If you want to build a form in React, you need to use this event to track
the value of input elements.
import React from "react";
function App() {
function handleChange(event) {
console.log(event.target.value);
}
return (
<input
type="text"
name="firstName"
onChange={handleChange}
/>
);
}
export default App;