Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update input fields based on calculation ReactJs

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading