4

consider that i have a data like this:

const[specs, setSpecs] = useState(['motherboard', 'ram', 'mouse'])

I need to somehow two way bind this to my input.

I was trying out something like this:

const handleOnChange = (e, spec, index) => {
  let data = specs;
  data[index] = e.target.value;
  setSpecs(data)
}

It does update in array but it doesn't reflect in the input box

{
  specs.map((spec, index) => {
    return <Row>
      <Col>
        <Form.Control key={spec} value={spec} 
          onChange={(e) => handleOnChange(e, spec, index)} type="text" />
        <br/>        
      </Col>
    </Row>
}
Hemanth
  • 141
  • 2
  • 13
  • 2
    You don't really bind things two ways in react. What you need to do is put the data on the state of the component, and in your handleOnChange function call the this.setState function of this component to update the data. This will rerender the component and the controls inside it. – Jakub Rusilko Oct 21 '20 at 10:55

1 Answers1

-1

Finally I solved myself.

    const handleOnChange = (e, spec, index) => {  
        let data = [...specs];
        data[index] = e.target.value;
        setSpecs(data);
}

The reason why I didn't get i was mutating the state

Hemanth
  • 141
  • 2
  • 13