Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 795
martin36 Avatar asked Jul 24 '17 19:07

martin36


People also ask

How do you set required props in React?

You can define default values for your props by assigning to the special defaultProps property: class Greeting extends React. Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } // Specifies the default values for props: Greeting.

How do I pass a prop to a component?

To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax.

How do I set props to default value?

The logical OR operator || is used to set a fallback value for the version prop whenever it is not passed. A default value of 16 has been set for the version prop. With this change, everything now works as expected.

Can we use PropTypes in functional component?

It's done the same way you do with Class Based Components import PropTypes from "prop-types"; const = function_name => {} function_name. propTypes = { prop_name : PropTypes. number . . . . . . . . . . . . . . } Hope This Helps !


1 Answers

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}
  />
);

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  element: PropTypes.arrayOf(PropTypes.element).isRequired
};
like image 188
pethel Avatar answered Oct 02 '22 00:10

pethel