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

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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