Set required requisites for the component

Let's say that I am creating a custom component like this:

const MyComponent = (props) => (
  <div
    className={props.name}
    id={props.id}>
    {props.children}
  </div>
)

      

And I need to props

contain the variables name

and id

, because otherwise I won't work (I now know this code will work anyway, but hypothetically say it won't).

Is there a way in React to require certain props to be passed to a component?

Perhaps this is what is obvious, but I could not find any information on this.

+3


source to share


1 answer


You can use PropTypes. It used to be part of React, but now it has its own npm package, https://www.npmjs.com/package/prop-types . This will give you a runtime error if no props are provided. It's also helpful because lint can alert you if you miss them.
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md



import React from 'react';
import PropTypes from 'prop-types'; 

const MyComponent = (props) => (
  <div
    className={props.name}
    id={props.id}>
    {props.children}
  </div>
);

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  element: PropTypes.arrayOf(PropTypes.element).isRequired
};

      

+2


source







All Articles