In menu/
the name of my invited people are not diplayed there is only the InfoIcon
in the Cell. I want to create a Popover
, when you click on the InfoIcon
, you get all the info of the invited people(name and location).
export default function Display() { const { dishes } = JsonData; const [anchor, setAnchor] = useState(null); const openPopover = (event) => { setAnchor(event.currentTarget); }; const data = useMemo( () => [ ... { //Problem: participants not displayed and click not working Header: "Invited", id: "invited", accessor: (row) => row.invited.map(({ name }) => name).join(", "), Cell: (props) => ( <div> <InfoIcon /> <Popover open={Boolean(anchor)} anchorEl={anchor} anchorOrigin={{ vertical: "top", horizontal: "left" }} transformOrigin={{ vertical: "bottom", horizontal: "right" }} > <Typography variant="h1">{props.participants}</Typography> </Popover> </div> ) }, ], [] ); return ( <Table data={dishes} columns={data} /> ); }
Here is my code
Advertisement
Answer
In addition to saving the clicked element into state so the Popover
component has an element ref it needs to also store in state which specific row’s participants to render into the popover. Currently the code is using a singular boolean value for all the popovers. Use the row.id
to open a specific popover.
Don’t forget to add the “anchor” state to the dependency array so the popover gets the latest state.
function Display() { const { menus } = JsonData; const [anchorId, setAnchorId] = useState(null); const [anchorEl, setAnchorEl] = useState(null); const openPopover = id => (event) => { setAnchorId(id); setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorId(null); setAnchorEl(null); }; const data = useMemo( () => [ { Header: "Id", accessor: (row) => row.id }, { Header: "Invited", id: "invited", accessor: (row) => row.invited, Cell: (props) => ( <div> {props.value.map(({ name }) => name).join(", ")} <InfoIcon onClick={openPopover(props.row.id)} /> <Popover open={anchorId === props.row.id} onClose={handleClose} anchorEl={anchorEl} anchorOrigin={{ vertical: "top", horizontal: "left" }} transformOrigin={{ vertical: "bottom", horizontal: "right" }} > <Typography variant="h6"> {props.value.map(({ name, location }) => ( <div key={name}> <p>{name}</p> <p>Location: {location}</p> </div> ))} </Typography> </Popover> </div> ) }, { Header: "Title", accessor: (row) => ({ title: row.title, id: row.id }), Cell: ({ value }) => ( <Link to={{ pathname: `/menu/${value.id}` }}>{value.title}</Link> ) } ], [anchorEl, anchorId] ); const initialState = { sortBy: [ { desc: false, id: "id" }, { desc: false, id: "invited" }, { desc: false, id: "title" } ] }; return ( <Table data={menus} columns={data} initialState={initialState} withCellBorder withRowBorder withSorting withPagination /> ); }