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.
You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.
If we want to pass/call the multiple props methods in a single event handler in ReactJS then there are two ways to make it work. Method 1: We can make a separate method for the event and call all the props method in that method.
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> ); } }
You can set icon size with React.cloneElement
API
class MenuItem Extends React.Component { render() { return( <div className="MenuItem"> {React.cloneElement(this.props.icon, { size: 24 })} </div> ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With