Andrey Fedorov
Andrey Fedorov

Reputation: 9669

How do I check if a React component is expecting a prop?

I'm trying to wrap a variety of components in a Modal, which will pass closeModal properties into any children which support it.

Currently I'm following this post and using a JS property closesModal to signal that the parent should pass in the closer method, i.e.:

React.Children.map(
  this.props.children,
  child => (
    child.closesModal ?
      React.cloneElement(child, { closeModal: this.close }) :
      child
  )
)

Is this a fair way to go about accomplishing what I want, and is there a way to introspect a React component to see whether or not it expects a property?

Upvotes: 1

Views: 830

Answers (1)

Ved
Ved

Reputation: 12103

Here is a sample example for same:

import PropTypes from 'prop-types';  // for React version React >=v15.5 

class Greeting extends React.Component {

  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  // This indicates name should be passed as props from parent. 
  name: PropTypes.string.required
};

Docs: https://facebook.github.io/react/docs/typechecking-with-proptypes.html

Upvotes: 3

Related Questions