How to add additional props to a React element passed in as a prop?
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.
2 answers
-
answered 2018-04-14 14:24
Denis
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> ); } }
-
answered 2018-04-14 14:24
Seth McClaine
You should be able to update the child prop before render....
class MenuItem Extends React.Component { render() { const icon = this.props.icon; icon.props.size = 24; //assuming size is static return( <div className="MenuItem"> {icon} </div> ); } }