Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropTypes in functional stateless component

Without using class, how do I use PropTypes in functional stateless component of react?

export const Header = (props) => (
   <div>hi</div>
)
like image 201
Alan Jenshen Avatar asked Oct 05 '22 14:10

Alan Jenshen


People also ask

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.

How do you use PropTypes in a functional component React?

Using PropTypes in React PropTypes is React's internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.

What does the PropTypes check do for the component?

PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.

Are functional components stateless?

A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.


2 Answers

The official docs show how to do this with ES6 component classes, but the same applies for stateless functional components.

Firstly, npm install / yarn add the prop-types package if you haven't already.

Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.

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

const Header = ({ name }) => <div>hi {name}</div>;

Header.propTypes = {
  name: PropTypes.string
};

// Same approach for defaultProps too
Header.defaultProps = {
  name: "Alan"
};

export default Header;
like image 173
Mike Avatar answered Oct 19 '22 02:10

Mike


It isn't different with the stateful, You can add it like:

import PropTypes from 'prop-types';
Header.propTypes = {
  title: PropTypes.string
}

Here is a link to prop-types npm

like image 32
I Putu Yoga Permana Avatar answered Oct 19 '22 03:10

I Putu Yoga Permana