Search code examples
javascriptreactjscomponents

Get Value of array name in react js in functional componet


How can I get value with input name array in functional component based react js.

Here is my code

<form method="post" onSubmit={handleSubmit}>
   <input type="text" name="otp[]"  placeholder="0" className="form-control inputs"/>
   <input type="text" name="otp[]"  placeholder="0" className="form-control inputs"/>
   <input type="text" name="otp[]"  placeholder="0" className="form-control inputs"/>
   <input type="text" name="otp[]"  placeholder="0" className="form-control inputs"/>
   <button className="btn btn-default text-light pos-rel">Verify</button>
 </form>

Thanks in advance


Solution

  • You should store input values with state, for this i suggest an object.

    const [values, setValues] = useState({otp1: 0, otp2: 0, ...restOfTheInputs });
    

    Then you can trigger a change of state when an input is changed by adding a onChange prop to your inputs. (You should also give these inputs a unique name)

    <input type="text" name="otp1" value={values.opt1} onChange={(e) => handleInput(e)} />
    

    in this function you will want to update state with the new value for the input replacing any old value while keeping any values from the other inputs.

    const handleInput = (event) => {
        const {name, value} = event.target;
        setValues(currentValue => ({...currentValue, ...{name: value}}))
    }