I am passing a react element as a prop to another element. In the child element that receives the prop, I need to set additional props to that element.
For example:
Parent class
class Menu Extends React.Component {
render() {
return(
<div className="Menu">
<MenuItem icon={<MdInbox />} />
<MenuItem icon={<MdDrafts />} />
<MenuItem icon={<MdTrash />} />
</div>
);
}
}
Child class
class MenuItem Extends React.Component {
render() {
return(
<div className="MenuItem">
{this.props.icon} // I want to set the icon's size prop here
</div>
);
}
}
this.props.icon
is a React element (<MdInbox />
, <MdTrash />
, etc), and it allows for a property size
. I want to set the size
property in the MenuItem
class, as opposed to passing the prop in from the parent like this: <MenuItem icon={<MdInbox size={24} />}
. I'd prefer just to set the size in one place only, within the MenuItem
class.
Pass in the component constructor instead of an instance:
class Menu extends React.Component {
render() {
return(
<div className="Menu">
<MenuItem icon={MdInbox} />
<MenuItem icon={MdDrafts} />
<MenuItem icon={MdTrash} />
</div>
);
}
}
The child class:
class MenuItem extends React.Component {
render() {
// This constant must begin with a capital,
// it’s how React distinguishes HTML elements from components.
const Icon = this.props.icon;
return(
<div className="MenuItem">
<Icon size={24} />
</div>
);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments