Home > Net >  Update input fields based on calculation ReactJs
Update input fields based on calculation ReactJs

Time:07-30

I have two input fields and allowing user to type on either inputs to perform meters to kilometers conversion. I'm trying to use useEffect to watch for changes and update either input field but it's not functioning correctly.

import React, { useState, useEffect } from "react";
import './App.css';

function App() {
  const [value, setValue] = useState('');
  const [value2, setValue2] = useState('');
  useEffect(() => {
    let res = parseInt(event.target.value) * 1000;
    setValue2(res.toString());
  }, [value])
  useEffect(() => {
    let res = parseInt(event.target.value) / 1000;
    setValue(res.toString());
  }, [value2])
  const onChange = (event) => {
    setValue(event.target.value);
  };
  const onChange2 = (event) => {
    setValue2(event.target.value);
  };
  return (
    <>
      <div>Meters</div>
      <input value={value} onChange={onChange} />
      <div>Kilometers</div>
      <input value={value2} onChange={onChange2} />
    </>
  );
}

export default App;

CodePudding user response:

you don't need useEffect to achieve what you want :

import React, { useState } from "react";

function App() {
  const [value, setValue] = useState(null);
  const [value2, setValue2] = useState(null);

  const onChange = (event) => {
    setValue(event.target.value);
    setValue2(event.target.value / 1000);
  };
  const onChange2 = (event) => {
    setValue2(event.target.value);
    setValue(event.target.value * 1000);

  };

  return (
    <>
      <div>Meters</div>
      <input value={value} onChange={onChange} />
      <div>Kilometers</div>
      <input value={value2} onChange={onChange2} />
    </>
  );
}

export default App;

sandbox example here

  • Related