Reputation: 29
I am doing a conditional rendering in my code in which i need to change the component called according to the state when it changes every time. Default option is Unpaid. When I select Paid 1st time state changes to the paid and component also changes to paid but after that if I changes to Unpaid state is changing but the Component is stuck to Paid. What can be the issue? Code is attached.
import React, { useState } from "react";
import Paid from "./Paid";
import Unpaid from "./Unpaid";
const Payment = () => {
const [paid, setPaid] = useState(0);
return (
<React.Fragment>
<div className="container">
<br />
<div className="row">
<div className="col-sm-4">
<select
className="browser-default custom-select"
onChange={(option) => setPaid(option.target.value)}
required
>
<option value="0">Unpaid</option>
<option value="1">Paid</option>
</select>
</div>
<div className="col-sm-8"></div>
</div>
<br />
<div>{paid ? <Paid /> : <Unpaid />}</div>
</div>
</React.Fragment>
);
};
export default Payment;
Upvotes: 0
Views: 264
Reputation: 1
add +
to convert the string value to a number 0
or 1
onChange={(option) =>{let val=+option.target.value ;setPaid(val);}}
let a="0"
let b="1"
console.log(+a,+b)
let c=+a
c? console.log("test 1"):console.log("test 2")
Upvotes: 1
Reputation: 675
Look this way to update your state
({ target: { value } }) => setPaid(value)
Upvotes: 0
Reputation: 1482
You'll need to parse option.target.value
, as it's always evaluating to true
since inputs always output a string, which is always truthy.
onChange={(option) => setPaid(JSON.parse(option.target.value))}
Upvotes: 1