'How can I set the value of a Form.Item without a form object in Ant.Design?
I have custom Form Item component and I want to add hidden input, but I can't update value without Ant Form object (Form.useForm();
const selectBefore = (
<Select
onChange={value => {/*HOW TO SET NEW VALUE FOR <Input name='term-type'/> ?*/}}
>
<Select.Option value="date">Date</Select.Option>
<Select.Option value="number">Number</Select.Option>
</Select>
);
const InputType = termType === 'date' ? DateInput : Input;
return (
<>
<InputType
addonBefore={selectBefore}
{...rest}
/>
<Form.Item
name='term-type'
initialValue={termType}
style={{display: 'none'}}
>
<Input
type="text"
value={termType}
/>
</Form.Item>
</>
);
Solution 1:[1]
You can remove the Input part altogether instead of keeping it hidden to use its value. Try this:
<Select onChange={value => setTermType(value)}}>
<Select.Option value="date">Date</Select.Option>
<Select.Option value="number">Number</Select.Option>
</Select>
Then you can use termType as state, and it will be updated as the Select value changes. I suggest that you should add a placeholder or default initial value to Select component as
<Select defaultValue="date" onChange={value => setTermType(value)}}>
<Select.Option value="date">Date</Select.Option>
<Select.Option value="number">Number</Select.Option>
</Select>
Solution 2:[2]
You can use useState hook and set the value to the state and don't use Form.useForm() and Form.Item at all:
const [ termType, setTermType ] = useState("");
...
<Select onChange={value => setTermType(value)}}>
<Select.Option value="date">Date</Select.Option>
<Select.Option value="number">Number</Select.Option>
</Select>
...
<Input
type="text"
value={termType}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Berkay G. |
| Solution 2 |
