Sohaib
Sohaib

Reputation: 29

React - JSX is not changing on conditional rendering

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

Answers (3)

Boussadjra Brahim
Boussadjra Brahim

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

Marco Mesen
Marco Mesen

Reputation: 675

Look this way to update your state

({ target: { value } }) => setPaid(value)

Upvotes: 0

Jay Kariesch
Jay Kariesch

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

Related Questions