Home > Mobile >  Using useState with if conditionals and return only two possible numbers
Using useState with if conditionals and return only two possible numbers

Time:04-15

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; 

                                                         

CodePudding user response:

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.

CodePudding user response:

Just change this (you initialize a string)

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

By this

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

  • Related