martin36 martin36 - 3 years ago 104
React JSX Question

Set required props on component

Say that I create a custom component like this:

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


And I need to make sure that
props
contain the variables
name
and
id
, because otherwise what I want to do is not going to work (now I know that this code will work anyhow, but hypothetically say that it won't).

Is there a way in React to demand that certain props are passed to a component?

Maybe this is something that is obvious, but I couldn't find any information about it.

Answer Source

You can use PropTypes. It was earlier a 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 ther props are not provided. Its also useful, because linters can warn 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
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download