Using state with form fields in react
lets understand the two approaches here for managing multiple form field state.
1- Lets suppose we have multiple field in our forms, so one way is, inorder to manage those feilds, we can make use of multiple state as shown below, also I have intialized each field with empty string here, because either way you passit any, it would store it as string:
const [bookName, setBookName]=useState(' ');
const [authorName, setAuthorName]=useState(' ');
const [amount, setAmount]=useState(' ');
2- Or other way is to use single state instead, with field values as object as shown below:
const [userInput, setUserInput]=useState({
bookName : ' ',
authorName : ' ',
amount : ' '
});
Important tips : While updating the input field using setter function in this case (in second approach i.e using single state) make use of es6 (spread operator) as shown below:
setUserInput({
...userInput,
bookName: value //value here refers to the value that you want to update for this field.
}); //using spread operator here will help us to retain the existing form value and will only update the required field, here as bookName in this case.
Also if your state depends on previous state then the best way to handle it is as shown below:
setUserInput((previousState)=>{
return {previousState, bookName: value //value here refers to the value that you want to update for this field. }
}); //this setter function that is provided to us from useState hook also provides us with previousState, that we used in above function.
thanks, Happy coding!