miouri
miouri

Reputation: 409

Math Operation with React States

I have a state that gets a value from an input. Is it possible to make a mathematical operation? I guess the input saves a numerical string in the state but I don´t know how to convert the state to an int. With parseInt it doesn´t work

export default function Bill(){

const [bill,setBill]=useState(0)
const [tip,setTip]=useState(0)
const [people,setPeople]=useState(0)




function reset(){
    setBill(0)
    setTip(0)
    setPeople(0)
    
}
    
return(
    <div>
    <div>Bill
        <input type="text"  onChange= {e=>setBill(e.target.value)}/>
    </div>
      
    <div>
      Select Tip %
      <button onClick={()=>setTip(0.05)}>5%</button>
      <button onClick={()=>setTip(0.1)}>10%</button>
      <button onClick={()=>setTip(0.15)}>15%</button>
      <button onClick={()=>setTip(0.25)}>25%</button>
      <button onClick={()=>setTip(0.5)}>50%</button>
      <input type="text" placeholder='Custom'  onChange={e=>setTip(e.target.value/100)}/>
    </div>
    
  <div>
        Number of People
        <input type="text"  placeholder='0'  onChange={e=>setPeople(e.target.value)} />
    </div>

    <div>
    <div>
    Tip Amount
    /person
    <div>{parseInt(bill)*parseInt(tip)/parseInt(people)}</div>
    </div>
    <div>
        Total
        /person
        <div></div>
    </div>
    <button onClick={reset}>Reset</button>
    </div>
  </div>
)
} 

Upvotes: 1

Views: 668

Answers (1)

isaacsan 123
isaacsan 123

Reputation: 1168

First of all, I'd change the type of your inputs from "text" to "number". That way, the user can't input anything that isn't numeric, and because you're using React, you won't have to worry about converting the input when you change the state.

Also, there's a bit of a bug with your tip state. You're trying to allow the user to input a number, and with setTip, you're trying to automatically convert that number into a decimal. The problem with that is that you're not allowing the user to input a full number before converting that number into a decimal to represent the tip.

The easiest way to fix these 2 issues would be to just change your inputs to type number like I mentioned and add min, max (optional), and step parameters to said input. That's how you can create a decimal input.

Here's an example:

<input 
  type="number" 
  min={0}
  max={1}
  step={0.01}
  value={tip} 
  onChange={e => setTip(e.target.value)}
/>

This way, you can get the tip saved as a decimal in your state without interfering with what the user is trying to input.

Finally, as you can see in the example above, you should also have a value attribute in each of your inputs. That way, each of your input components will be controlled, meaning that the value shown inside them represents their respective states, which is good practice in React.

Upvotes: 1

Related Questions