reactjsinputcontrolled-component

React controlled vs. uncontrolled input form


First of all consider I'm fairly new to react.

I'm building a form with a field is an input. When entering the text into the input I recieve a message saying

Warning: A component is changing an uncontrolled input to be controlled

I look into the docuemnentaion but I'm not able to understand why it behaves like that. Can some one help me understand?

here is the input field

<div>
      <input type="text"
       name = 'brand'
       onChange = {(e) => inputChange(e)}
       value = {submit.brand}
       required />
    </div>

here is the function to handle it

{submit, SetSubmit} = useState([)
const inputChange = (e) => {
const { name, value } = e.target;
setSubmit(submit => ({...submit, [name]: value}))}

many thanks in advance for helping me understand


Solution

  • You can refer here for usage of controlled inputs in functional component.

    You are initializing the state incorrectly,

    const [submit, SetSubmit] = useState('');
    

    Also, the onChange event should be handled as

       <div>
          <input type="text"
           name = 'brand'
           onChange = {inputChange}
           value = {submit}
           required />
        </div>
    

    And function as,

    const inputChange = (e) => {
      setSubmit(e.target.value)
    }
    

    In case of multiple inputs, please refer the following example :

    import React, { useState } from "react";
    
    const initialValues = {
      company: "",
      position: "",
      link: "",
      date: "",
      note: "",
    };
    
    export default function Form() {
      const [values, setValues] = useState(initialValues);
    
      const handleInputChange = (e) => {
        const { name, value } = e.target;
        setValues({
          ...values,
          [name]: value,
        });
      };
    
      return (
            <form>
              <input
                value={values.company}
                onChange={handleInputChange}
                name="company"
                label="Company"
              />
              <input
                value={values.position}
                onChange={handleInputChange}
                name="position"
                label="Job Title"
              />
               // ... Rest of the input fields
              <button type="submit"> Submit </button>
            </form>
      );
    }