1

I wanna change my layout between grid and list with 2 buttons. I am very new to react, and I thought to use State, my button logic seems to work(when i console.log) but I don't know how to change div classNames based on State. I tried something but it doesnt work(see below). Whatever button I click grid or list my style changes but only for the first click, then nothing happens.

const Restaurants = () => {
    const [isGrid, layoutToggle] = useState({
        value: true
    });


    console.log(isGrid);

    return (
        <div className="restaurants">

            <button onClick={() => layoutToggle({ isGrid: true })}>
                Grid
            </button>
            <button onClick={() => layoutToggle({ isGrid: false })}>
                List
            </button>

            <div className={isGrid["value"] ? "layout-grid" : "layout-list"}>
                {restaurants.map(restaurant => (
                    <Restaurant/>
                ))}
            </div>
        </div>
    );
};

1 Answer 1

1

The problem is in the button elements, You should the change the state with the value property not the isGrid property.

<button onClick={() => layoutToggle({ value: true })}>
   Grid
</button>
<button onClick={() => layoutToggle({ value: false })}>
   List
</button>
Sign up to request clarification or add additional context in comments.

4 Comments

thanks man that was it. Is there a better way to use useState (name and value) for what i did?
The more simplified way is instead of using object we can directly use boolean value as state; const [isGrid, layoutToggle] = useState(true); <div className={isGrid ? "layout-grid" : "layout-list"}>
ok but if i use const [isGrid, layoutToggle] = useState(true) how do i use layoutToggle() to set true or false?
onClick={() => layoutToggle(true)} // true or false based on the type of button

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.