Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda