Home > front end >  reactjs onchangevent and keypress event
reactjs onchangevent and keypress event

Time:11-25

Encountered a problem in react. There area two input Textfield in the same row with labels (A, B) having an initial null value. Then how we can achieve this?

  • if the user inputs value in text field "A", the values of text field B should be automatically zero
  • and then vice versa

CodePudding user response:

You can achieve this using onChange event and useState hook. in the below example, I defined a onChange event where I set A and B with what you typed and zero respectively.

import { useEffect, useState } from "react";

export default function App() {
  const [a, setA] = useState();
  const [b, setB] = useState();

  function AKeyPress(e) {
    e.preventDefault();
    setB("0");
    setA(e.target.value);
  }

  function BKeyPress(e) {
    e.preventDefault();
    setA("0");
    setB(e.target.value);
  }

  return (
    <div className="App">
      <header className="App-header"></header>
      <h1>Hello</h1>
      A <input type="text" onChange={AKeyPress} value={a} />
      B <input type="text" onChange={BKeyPress} value={b} />
    </div>
  );
}

CodePudding user response:

You could store the values in state and if any of these changes, set the current one to the updated value, and delete the other one. You can use the onChange event to track changes and the event.target to get the field value.

Check out the example below:

function App() {
  const [field1, setField1] = React.useState('');
  const [field2, setField2] = React.useState('');

  function handleChange(event) {
    if (event.target.name === 'field1') {
      setField2('');
      setField1(event.target.value);
    }
    if (event.target.name === 'field2') {
      setField1('');
      setField2(event.target.value);
    }
  }

  return (
    <form>
      <label>
        Field 1
        <input
          type="text"
          name="field1"
          onChange={handleChange}
          value={field1}
        />
      </label>
      <label>
        Field 2
        <input
          type="text"
          name="field2"
          onChange={handleChange}
          value={field2}
        />
      </label>
    </form>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You could also use an array as the state:

function App() {
  const [inputs, setInputs] = React.useState([{
    id: 'input1',
    value: '',
  }, {
    id: 'input2',
    value: '',
  }]);

  function handleChange(event) {
    let updatedInputs = inputs.map((input) =>
      input.id === event.target.name
        ? { ...input, value: event.target.value }
        : { ...input, value: '' }
    );
    setInputs(updatedInputs);
  }

  return (
    <form>
      {inputs.map((input) => (
        <label key={input.id}>
          {input.id}
          <input
            type="text"
            name={input.id}
            onChange={handleChange}
            value={input.value}
          />
        </label>
      ))}
    </form>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related