Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only allow children of a specific type in a react component

I have a Card component and a CardGroup component, and I'd like to throw an error when CardGroup has children that aren't Card components. Is this possible, or am I trying to solve the wrong problem?

like image 482
bigblind Avatar asked Dec 08 '14 20:12

bigblind


People also ask

How do you pass children to a react component?

Children are props If you want to pass things to this button, you would use a prop. If you want to make our button say more than just "I am a button," you can pass children to it. By passing children in this way, you are passing it to the component by position.

What is Prop children in React?

Essentially, props. children is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component. These kinds of components are identified by the official documentation as “boxes”.

What is displayName in React?

displayName. The displayName string is used in debugging messages. Usually, you don't need to set it explicitly because it's inferred from the name of the function or class that defines the component.

Can we render two child components in React?

React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components.


2 Answers

You can use the displayName for each child, accessed via type:

for (child in this.props.children){   if (this.props.children[child].type.displayName != 'Card'){     console.log("Warning CardGroup has children that aren't Card components");   }   } 
like image 37
Mark Avatar answered Sep 28 '22 01:09

Mark


For React 0.14+ and using ES6 classes, the solution will look like:

class CardGroup extends Component {   render() {     return (       <div>{this.props.children}</div>     )   } } CardGroup.propTypes = {   children: function (props, propName, componentName) {     const prop = props[propName]      let error = null     React.Children.forEach(prop, function (child) {       if (child.type !== Card) {         error = new Error('`' + componentName + '` children should be of type `Card`.');       }     })     return error   } } 
like image 157
Diego V Avatar answered Sep 28 '22 01:09

Diego V