Jun 23, 2020 09:39 PM
Hi all - I’m new to react and web dev in general. I have created a Box with a FormField inside. It displays correctly but I cannot seem to enter any text in the input field. It is not taking any values, like it is read-only. Does anyone know what I am doing wrong? Here is my code:
<Box
padding="20px"
border="thick"
borderRadius="large"
>
<div>
<FormField
label= {formLabel}
>
<Input
placeholder = {descriptionPlaceHolder}
value = {addDescription}
onChange={e => addDescription = e.target.value}
/>
<Button
style = {{marginTop: 10}}
onClick = {() => {}}
>
Add
</Button>
</FormField>
</div>
</Box>
Solved! Go to Solution.
Jun 23, 2020 10:06 PM
Solved it - I do not yet quite understand the state and how react deals with it. You have to tajke the onChange via the state, So adding a useState and setState solved it for me:
const [descript, setdescript] = useState("");
…
onChange={e => setdescript(e.target.value)}
Jun 23, 2020 09:42 PM
Try taking the button out of the form field, I think form fields only support one child element (your input).
Jun 23, 2020 09:47 PM
Thanks Kamille - I have tried that already and it has the same result. The field remains inactive.
Jun 23, 2020 10:06 PM
Solved it - I do not yet quite understand the state and how react deals with it. You have to tajke the onChange via the state, So adding a useState and setState solved it for me:
const [descript, setdescript] = useState("");
…
onChange={e => setdescript(e.target.value)}
Jun 24, 2020 04:55 PM
In React controls such as inputs should normally be “controlled”. That means that there is always a value kept in state (through the useState
hook) that is passed to the value of the input. This model of always rendering your data in a single direction makes things easy to reason about your app once it grows. For instance you can use the value somewhere else, and it isn’t just locked in your input, for instance:
const [value, setValue] = useState('');
return (
<div>
<Input
value={value}
onChange={e => setValue(e.target.value)}
/>
<p>Here is your value always in sync: {value}</p>
</div>
):