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?
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.
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”.
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.
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.
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"); } }
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 } }
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