Search code examples
javascriptreactjsantdant-design-pro

How to change value of select input which is inside a form balise (ant design)


I'm searching how to change the value of my select input inside of a form balise (with ant design library).

 let [value, setValue] = useState(null)

<Form.Item name="value" rules={[{ required: true, message: 'Veuillez choisir une valeur !' }]}
                   label="Type">
     <Select value={value} onChange={e => setValue(e)}>
         <Option value="pp">Personne physique</Option>
         <Option value="mp">Personne morale</Option>
     </Select>
</Form.Item>

<Button type="primary" onClick={setValue('pp')}>Click me</Button>

When i'm clicking, nothing happen, the value stay the old one.

But if I delete the <Form.Item> balise, it work correctly.

Any idea ?

Thank you


Solution

  • you can do like this

    let [value, setValue] = useState(null)
    
    const handleFormValuesChange = (changedValues) => {
      const formFieldName = Object.keys(changedValues)[0];
      if (formFieldName === "typeCeso") {
        setValue(changedValues[formFieldName]);
      }
    };
    
    
    
    <Form form={form} name="form" onFinish={onFinish} onValuesChange={handleFormValuesChange}>
      <Form.Item
      name="typeCeso"
      rules={[{ required: true, message: "Veuillez choisir une valeur !" }]}
      label="Type"
    >
      <Select>
        <Option value="pp">Personne physique</Option>
        <Option value="mp">Personne morale</Option>
      </Select>
    </Form.Item>
    </Form>