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

118
Visualizações
Using useState with if conditionals and return only two possible numbers

I'm having trouble getting this to work as I want. So basically I have an input field with a 0 prefixed. I need it to return 0 if there isn't a 1 inserted (only in that case it should return 1). But I can't change the input after I write a number and console.log doesn't return only 0 or 1. This is the code:

import { useState } from "react";
import "./App.css";

const App = () => {
  const [inputValue, setInputValue] = useState('0');

  const changeInputValue = (event) => {
    let newInput = event.target.value === "1" ? 1 : 0;
    setInputValue(newInput);
    console.log(newInput);
  };

  return (
    <div className="App">
      <div>
        <label for="input1">Enter 0 or 1:</label>
        <input
          type="number"
          id="input1"
          value={ inputValue }
          onChange={(e) => changeInputValue(e)}
        />
      </div>
    </div>
  );
};

export default App; 

                                                         
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Check that you are using '0' as a default value not 0 and '0' is a string, either use parseInt() or remove the quotation marks also you should convert the value of the input to a number also. I also recommend using htmlFor instead of for in your label.

about 4 years ago · Santiago Trujillo Relatório

0

Just change this (you initialize a string)

const App = () => { const [inputValue, setInputValue] = useState('0');

By this

const App = () => { const [inputValue, setInputValue] = useState(0);

about 4 years ago · Santiago Trujillo 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