Assume I have three inputs and a button, I want to empty input values when button is clicked.
const [input_value,set_input_value] = useState({
input1:'',
input2:'',
input3:''
})
const inputs_handler = (e) => {
let name= e.target.name;
let value= e.target.value;
input_value[name] = value;
set_input_value(input_value);
}
const clear_input_values = () => {
// First try
/*
set_input_value({
input1:'',
input2:'',
input3:''
})
*/
//SECOND TRY
set_input_value(prevState => ({
...prevState,
input1:'',
input2:'',
input3:''
}))
// console.log shows that the values of state didn't get empty from the first click, but does in
the second
console.log(input_value)
}
<div>
<input onChange={inputs_handler} type='text' name='input1' />
<input onChange={inputs_handler} type='text' name='input2' />
<input onChange={inputs_handler} type='text' name='input3' />
<input onClick={clear_input_values} type='submit' />
</div>
I can use document.getElementsById(id)[0].value=''; to empty the input's value but I don't think this is the proper way to do it in a React project.
This is really confusing me, i appreciate if someone provides a clear example or a link to an example that explains how the state works and when it does render the component. since i believe i changed the state value before i use set_inputvalues() method.
<input onChange={inputs_handler} type='text' value={input_values.input1} name='input3' />i woudn't be able to change the value