2

Firstchild file:

  const [qtd, setQtd] = useState(props.number);
  function updateNumber(){
    props.setNumber(qtd);
  }

  const handleChange = event => {
    setQtd(event.target.value);
  };


return(
         <input type="number" name="integerTimes" className="integerTimes" placeholder='Insira aqui' id="qtd" onChange={handleChange}/>
        <button id="submitTimes" onClick={updateNumber}>Enviar</button>
);

Parent Component:

const [number, setNumber] = useState(0);

if (number>0){
    return (
      <div id='main'>
        <div>
          <Firstchild setNumber={setNumber} number={number}/>
          <SecondChild number={number}/>
        </div>
      </div>
    );
  }

the problem is, i need 'number' to pass to other child component, but apparently when the parent re-render i lose the update that i made in the first child component. How can i mantain the value of 'number' after changing in the child component?

c4xp
  • 83
  • 5

1 Answers1

0

You should have single source of truth especially when you are working with inputs because and inputs have there local state and you have to reference it to an external source in order to work properly.

reference your input's value to your parents state.

return(
         <input type="number" value={props.number} />
);
Moein Moeinnia
  • 1,945
  • 3
  • 10
  • 26
  • This does not allow to write something in the text field without it being 'submitted' to the parent. In essence the 'submit' button does nothing in this case. – Rotem Jun 20 '22 at 16:46
  • wrap your child elements in side `
    ` tag , inside parent component
    – Moein Moeinnia Jun 21 '22 at 08:40