1.

Explain type-checking with PropTypes in React?

Answer»

JavaScript is a loosely-bound language, which causes many errors in code. So, we should implement type-check, for different props been passed from Parent to Child component. Earlier it used to be a part of React library but since React v15.5, it has moved as a separate library. So, we need to npm install it and then import it by-

import PropTypes from ‘prop-types’;

Let consider the below example for PropType.

import React from ‘react’; class ReactProptypesDemo extends React.Component {    render() {    return (      <div>        <TestForProptypes          str="HRIDAY"          strOrNumber={10}            arr={[5,6,2]}          arrOfObject={[{name: "Chinu", age: 36}, {name: "Shik", age: 35}]}        />      </div>    )  } } CONST TestForProptypes = (props) => { return (   <React.Fragment>        <h3>{props.str}</h3>        <H4>{props.strOrNumber}</h4>        <div>{props.arr.map(ITM=> <li key={itm}>{itm}</li>)}</div>        <div>{props.arrOfObject.map(itm=> <li key={itm.age}>{itm.name}</li>)}</div>      </React.Fragment>      ); } TestForProptypes.propTypes = { str: PropTypes.string,  strOrNumber: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),  arr: PropTypes.arrayOf(PropTypes.number),  arrOfObject: PropTypes.arrayOf(PropTypes.shape(   {         name: PropTypes.string,          age: PropTypes.number        }  )) } ReactDOM.render(<ReactProptypesDemo />, document.querySelector("#app"))

Here we have a parent component ReactProptypesDemo which is passing props to TestForProptypes. So, for each prop, we check whether it is the correct type or not.

In TestForProptypes.propTypes , we check for each prop. 

Like for the “str” prop, we can check by -

str: PropTypes.string

For the array prop “arr” we can check as -

arr: PropTypes.arrayOf(PropTypes.number)

For the array of object prop “arrOfObject” we can check as -

arrOfObject: PropTypes.arrayOf(PropTypes.shape(     {         name: PropTypes.string,          age: PropTypes.number        }  ))


We have a check ALSO for String or Number prop “strOrNumber” as below -

strOrNumber: PropTypes.oneOfType([PropTypes.string, PropTypes.number])

if we pass “boolean” to it instead of string or number.

<TestForProptypes          str="Nabendu"          strOrNumber={true}            arr={[3,1,2]}          arrOfObject={[{name: "Nabs", age: 36}, {name: "Shikha", age: 35}]}        />

We will get the below error in console.

Warning: Failed prop type: Invalid prop `strOrNumber` supplied to  `TestForProptypes`.      in TestForProptypes (created by ReactProptypesDemo)      in ReactProptypesDemo


Discussion

No Comment Found