Handle input change in React

React JS

The basic way to do this is by defining some state, and then handling the state update directly in the change event of the input control, like this:



const [loginState, setLoginState] = useState({username: ''});

...

<input type='text' id='username' onChange={ (e) => setState({...loginState, username: e.target.value }) } value={ loginState.username }   />

The better way would be to define a generic handler which is more readable and simple to maintain:



const [loginState, setLoginState] = useState({username: ''});

function changeLogin(e) {
	setLoginState({...loginState, [e.target.id]: e.target.value});
}

...

<input type='text' id='username' onChange={changeLogin} value={ loginState.username }   />

Post a Comment

Previous Post Next Post