1

I am trying to change value of input field based on another one and vice versa.

That's create issue, any changed value not displayed in input. Anything I type is not show by input field.

Following which I tried, You can see I am trying to change value of input 1 based on 2 and 2nd input value based on first:

import React, { useState, useEffect } from 'react';

const App = () => {
  
   useEffect(() => {
   
   //fetch api call here
   
   });

  const [firstVal, setFirstVal] = useState(0);
  const [secondVal, setSecondVal] = useState(0);
  
  const changeFirstValue = (e) => {
      setSecondVal(e.target.value / 2);
  }

  const changeSecondValue = (e) => {
      setFirstVal(e.target.value * 2);
  }

  return (
    <div>
      <input type='number' value={firstVal} onChange={changeFirstValue}></input>
      <input type='number' value={secondVal} onChange={changeSecondValue}></input>
    </div>
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Any help would be greatly appreciated.

2
  • Do you mean that you want those two input values to keep the 2 times relationship, no matter which is inputting? Commented May 11, 2020 at 12:17
  • @Sorry, I edited my question. I want change 2nd value on first change and first value on second change Commented May 11, 2020 at 12:42

2 Answers 2

1

If you want to show the division and multiplication relationship between these two elements. Try below code:

  const changeFirstValue = (e) => {
    setSecondVal(e.target.value);
    setFirstVal(e.target.value * 2);
  }

  const changeSecondValue = (e) => {
      setFirstVal(e.target.value);
      setSecondVal(e.target.value / 2);
  }

  return (
    <div>
      <input type='number' value={firstVal} onChange={changeSecondValue}></input>
      <input type='number' value={secondVal} onChange={changeFirstValue}></input>
    </div>
  );
Sign up to request clarification or add additional context in comments.

1 Comment

0

From what I understood, I think you have to reverse the call of the two functions, so your code will look like this:

...
 <input type='number' value={firstVal} onChange={changeSecondValue}></input>
 <input type='number' value={secondVal} onChange={changeFirstValue}></input>
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.