sigsve February 2016

Specifying a prop to be a specific Component in React

I'm writing a component, and I wan't one of the props to alway be instances of A spesific component

class Component extends React.Component {
    static propTypes: {
        children: /*Only ChildComponents allowed*/
    }
}

class ChildComponent extends React.Component {}
<Component><div /></Component> // Should fail
<Component><div /><ChildComponent></Component> // Should fail
<Component><ChildComponent /></Component> // Should Succedd
<Component><ChildComponent /><ChildComponent /></Component> // Should Succedd

Answers


HazardouS February 2016

    children: React.PropTypes.instanceOf(ChildComponent)

Look here - https://facebook.github.io/react/docs/reusable-components.html.

Update As instanceOf is not working in your case, try this alternate approach -

In propTypes, allow any node -

children: React.PropTypes.node

Then in render method -

React.Children.map(children, (child, index) => {
  if (!React.isValidElement(child) 
       || !child.type 
       || child.type.displayName !== 'ChildComponent'){
    // Exterminate! Exterminate!
  }
}

Post Status

Asked in February 2016
Viewed 3,199 times
Voted 7
Answered 1 times

Search




Leave an answer