Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
sme Avatar asked Apr 14 '18 14:04

sme


People also ask

How do you pass components with props as props?

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.

Can we pass multiple props in React?

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.


Video Answer


2 Answers

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>         );     } } 
like image 133
Denis Avatar answered Sep 21 '22 15:09

Denis


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>         );     } } 
like image 43
Vadim Shvetsov Avatar answered Sep 22 '22 15:09

Vadim Shvetsov