Home > Net >  How to automatically update one input form based on another input form in react?
How to automatically update one input form based on another input form in react?

Time:09-27

How to update 2 interdependent input fields in react correctly? This code updates one input based on other but fails to update itself in the process.

    import { useState } from "react";

export default function App() {
  const [data1, setData1] = useState(0);
  const [data2, setData2] = useState(0);

  const inputEvent1 = (e) => {
    //e.preventDefault();
    const data2 = (e.target.value / 2).toString();
    setData2(data2);
    console.log("inputEvent1 "   e.target.value);
  };

  const inputEvent2 = (e) => {
    //e.preventDefault();
    const data1 = (e.target.value * 2).toString();
    setData1(data1);
    console.log("inputEvent2 "   e.target.value);
  };

  return (
    <form className="a">
      <div className="b">
        <h1 className="c">Data Changer</h1>
        <div className="">
          <div className="d" onChange={inputEvent1}>
            <p>Enter Data1:</p>
            <input
              name="dataField1"
              type="text"
              className="input"
              placeholder="Data1"
              value={data1.toString()}
            />
          </div>
          <div className="e" onChange={inputEvent2}>
            <p>Enter Data2:</p>
            <input
              name="dataField2"
              type="text"
              className="input"
              placeholder="Data2"
              value={data2.toString()}
            />
          </div>
        </div>
      </div>
    </form>
  );
}

CodeSandbox https://codesandbox.io/s/react-data-changer-2-input-boxes-q3pt9?file=/src/App.js:0-1298

CodePudding user response:

you just need another setState in your eventHandlers to set the changing field like this:

  const inputEvent1 = (e) => {
    const data2 = (e.target.value / 2).toString();
    setData1(e.target.value);
    setData2(data2);
  };

  const inputEvent2 = (e) => {
    const data1 = (e.target.value * 2).toString();
    setData2(e.target.value);
    setData1(data1);
  };

here is the working sandbox

  • Related