Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
reactjs onchangevent and keypress event

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
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda