PropTypes in functional stateless component

JavascriptReactjsReact PropsReact Proptypes

Javascript Problem Overview


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

export const Header = (props) => (
   <div>hi</div>
)

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

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

Solution 3 - Javascript

Same way you do in class based components:

   import PropTypes from 'prop-types';

   const funcName = (props) => {
       ...
   }
   funcName.propTypes = {
       propName: PropTypes.string.isRequired
   }

Note: You might have to install prop-types via npm install prop-types or yarn add prop-types, depending on the React version you are using.

Solution 4 - Javascript

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 !

Solution 5 - Javascript

Since React 15, use propTypes to validate props and provide documentation this way:

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

export const Header = (props={}) => (
   <div>{props}</div>
);
Header.propTypes = {
  props: PropTypes.object
};

This code on the assumption of default value props={} if no props provided to the component.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan JenshenView Question on Stackoverflow
Solution 1 - JavascriptMikeView Answer on Stackoverflow
Solution 2 - JavascriptI Putu Yoga PermanaView Answer on Stackoverflow
Solution 3 - JavascriptlokeshjView Answer on Stackoverflow
Solution 4 - JavascriptAshutosh TiwariView Answer on Stackoverflow
Solution 5 - JavascriptstorenthView Answer on Stackoverflow