I am using a map function inside the render function and upon a button click want to display the following div but I am unable to do. Earlier the onClick was triggered for the all the buttons inside the table of each row which ideally should not be the case.
Code :
const [list, setList] = useState(false)
const handleClick = (e) => {
e.preventDefault()
if(e.target.value) {
setList(!list)
}
setList(!list)
}
return (
<TableCell>
<Button className = 'active-select-option'
onClick = {handleClick}>Actions</Button>
{list ?
<div className = "select-option">
<ul id = 'action1' className = "select-option-inner rounded">
<li>Buy More</li>
<li>Sell </li>
<li>Next Li Tag</li>
<li>Edit Detials</li>
</ul>
</div> : ' ' }
</TableCell> )
The Problem is you're not passing e in handleClick. A way to do that is passing handleClick via Anonymous arrow function, so that you can reference it instead of invoking it.
<Button className = 'active-select-option'
onClick = {()=>handleClick(e)}>Actions</Button>
I don't see any issues with your code but you can simplify a bit the handleClick method (there's no need to handle the e.preventDefault()) and also use the && condition to display the <div>.
If list is true the <div> will be displayed, otherwise false is returned and the <div> is not displayed.
You can avoid to explicitly use the list variable with setList(!list) and instead use the value of the previous state provided as argument of the inner function of setList(l => !l)
If it's not going to work, could id be a css issue?
const [list, setList] = useState(false)
const handleClick = () => {
setList(l => !l);
}
return (
<TableCell>
<Button className = 'active-select-option'
onClick = {handleClick}>Actions</Button>
{list &&
<div className = "select-option">
<ul id = 'action1' className = "select-option-inner rounded">
<li>Buy More</li>
<li>Sell </li>
<li>Next Li Tag</li>
<li>Edit Detials</li>
</ul>
</div>}
</TableCell> )
Track the selected row id for displaying the action panel.
import "./styles.css";
import TableCell from "@mui/material/TableCell";
import { useState } from "react";
import { Button } from "@mui/material";
const data = [
{
id: 1001,
label: "Action1"
},
{
id: 1002,
label: "Action2"
}
];
export default function App() {
const [selectedId, setSelectedId] = useState();
const handleClick = (id) => {
setSelectedId(id !== selectedId ? id : null);
};
return (
<>
{data.map((val) => (
<div>
<TableCell>
<Button
className="active-select-option"
onClick={() => handleClick(val.id)}
>
{val.label}
</Button>
{selectedId === val.id && (
<div className="select-option">
<ul id="action1" className="select-option-inner rounded">
<li>Buy More</li>
<li>Sell </li>
<li>Next Li Tag</li>
<li>Edit Detials</li>
</ul>
</div>
)}
</TableCell>
</div>
))}
</>
);
}
Demo:- https://codesandbox.io/s/lucid-https-jkp84?file=/src/App.js:0-1114