Default Values in React
Sometimes you may want to make it so that by default the input already has some value. In this case, only the initial value of the input should be taken from the state, and the input itself should not be tied to this state.
To solve this problem, you need to use the defaultValue
attribute:
function App() {
const [value, setValue] = useState('text');
return <div>
<input defaultValue={value} />
</div>;
}
For checkboxes, there is a similar attribute defaultChecked
, with which you can set the initial:
function App() {
const [checked, setChecked] = useState(true);
return <div>
<input type="checkbox" defaultChecked={checked} />
</div>;
}
Try these attributes out for yourself.