How can I display the specific content that is assigned to a specific button in which if that specific button is clicked, it will display the assigned content of that specific button.
In my case, I have three buttons named "BBQ", "Bilao", and Chicken". These specific buttons contain their own specific content(which are also buttons but in a form of menu items containing their info).
Issue: My problem is that I cannot seem to display those specific content even if one of those specific buttons are clicked. For example, if "BBQ" will be clicked, it should display its specific menu item contents, the same process goes with "Bilao" and "Chicken".
I utilized a useState and an array of categories which contain the specific button names("BBQ", "Bilao", "Chicken) and also mapping the array. But all of these doesn't seem to work.
Source code:
import * as React from "react";
import { useState } from "react";
import { Stack } from "@mui/material";
import ButtonCategoryStyle from "./ButtonCategoryStyle";
import BBQButtons from "./categoryButtons/BBQButtons";
import BilaoButtons from "./categoryButtons/BilaoButtons";
import ChickenButtons from "./categoryButtons/ChickenButtons";
export default function HomeOrderPage() {
const categories = ["BBQ", "Bilao", "Chicken"];
const [myCategory, setMyCategory] = useState("");
return (
<div>
<Stack spacing={0} direction="row">
{categories.map((category) => (
<ButtonCategoryStyle
title={category.toLocaleUpperCase()}
key={category}
onClick={() => setMyCategory(category)}
/>
))}
</Stack>
<div>
<p>
{myCategory === "police" && <BBQButtons />}
{myCategory === "chef" && <BilaoButtons />}
{myCategory === "doctor" && <ChickenButtons />}
</p>
</div>
</div>
);
}
I based my code structure into this YT video, demo, and its Github source code:
https://www.youtube.com/watch?v=jRxoO-Zd0pQ (YT)
https://react-component-depot.netlify.app/react-basics/show-hide-elements (Demo)
There are similar Stack questions that involves this process but still most of them did not work well for me.
Hoping for your guides and responses since I am exploring MUI and React at the moment and it will be a big help for me. Thank you very much!
CodePudding user response:
There are two problems in your code.
{/*
HomeOrderPage.jsx
You have forgotten to change category names. Yours are "police, chef, doctor" right now.
*/}
{myCategory === "BBQ" && <BBQButtons />}
{myCategory === "Bilao" && <BilaoButtons />}
{myCategory === "Chicken" && <ChickenButtons />}
// styles removed just not to take space
// You need to use rest operator to pass all props
export default function ButtonCategoryStyle({ title, ...restProps }) {
return (
<Button
{...restProps}
>
{title}
</Button>
);
}
// Or you can just pass onClick method.
export default function ButtonCategoryStyle({ title, onClick }) {
return (
<Button
onClick={onClick}
>
{title}
</Button>
);
}