Search code examples
reactjsantd

How can i put value in input?


Why can't I put a value in the input? The problem is: I need to put a 'name' in <Form.Item> to apply the rules. Without that, the rules will not be able to work, but if you remove the name="userName" from <Form.Item the value appears at the input.

How can i solve that?

<Form autoComplete="off" layout="vertical" onFinish={handleFinish}>
  <Form.Item  name="userName" rules={getTextRule('name')}>
    <Input value={fields?.firstName} name="firstName" onChange={(e) => {
      handleInputChange(e)
    }} />
  </Form.Item>
</Form.Item>

Solution

  • If you use the form you can let Ant Form manage the state by removing the value & the onChange props on the <Input />.

    Else if you manage the state by yourself make sure to get the value from the e.target.value.

    ex:

    const [fields, setFields] = useState({})
    
    const handleOnChange = (e) => {
      setFields((state) => {
        ...state,
        [e.target.name]: e.target.value,
      })
    }
    
    return (
      <Input
        name="firstName"
        value={fields.firstName}
        onChange={handleOnChange}
      />
    )