Otavio Bonder
Otavio Bonder

Reputation: 1999

Add props to a children component

Maybe a dumb question, but how can I add props to a children component?

I.e., I created this component:

import React, { useState } from "react";
import { Menu, MenuItem } from "@material-ui/core";

export default function DashboardMenu({ children }) {
    const [open, setOpen] = useState(false);
    const [anchorEl, setAnchoEl] = useState(null);
    const handleClick = event => {
        setAnchoEl(event.currentTarget);
        setOpen(!open);
    };

    const handleClose = () => {
        setOpen(false);
    };

    return (
        <>
            {children}
            <Menu
                id="configMenu"
                keepMounted
                anchorEl={anchorEl}
                open={open}
                onClose={() => handleClose()}
            >
                <MenuItem onClick={handleClose}>Profile</MenuItem>
                <MenuItem onClick={handleClose}>My account</MenuItem>
                <MenuItem onClick={handleClose}>Logout</MenuItem>
            </Menu>
        </>
    );
}

I can call it like this:

<DashboardMenu>
  <Avatar
    style={{
      backgroundColor:
         theme.palette.secondary.main
    }}
  >
     {avatarId}
  </Avatar>
</DashboardMenu>

And the component will render the <Avatar> component with the style props.

My question is, inside the DashboardMenu component, how can I add one more props to the children, like {children onClick={handleClick}}?

Upvotes: 1

Views: 70

Answers (1)

Ga&#235;l S
Ga&#235;l S

Reputation: 1599

You can use React.cloneElement (doc here). You can pass props in the 2nd argument :

//...
return (
        <>
           {React.cloneElement(children, {/* props you want to add here*/})}}
            <Menu
                id="configMenu"
                keepMounted
                anchorEl={anchorEl}
                open={open}
                onClose={() => handleClose()}
            >
                <MenuItem onClick={handleClose}>Profile</MenuItem>
                <MenuItem onClick={handleClose}>My account</MenuItem>
                <MenuItem onClick={handleClose}>Logout</MenuItem>
            </Menu>
        </>
    );

You can find many examples of this in Material-UI such as here in MenuList.

Upvotes: 2

Related Questions