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.
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.
Share Improve this question asked Jul 24, 2017 at 19:23 martin36martin36 2,3634 gold badges22 silver badges31 bronze badges1 Answer
Reset to default 19You 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}
/>
);
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
element: PropTypes.arrayOf(PropTypes.element).isRequired
};