In this article, we will learn how to check props type using React.js.
Here, React has some built-in type checking abilities. to run type checking on the props for a component, you can use the prototype npm module.
First, we have to install the prop-types module like below.
npm i prop-types
Then, pass props parents component to child component and check the datatype by using prop-type like below code.
import './App.css'; import React from 'react' import Reactstrapcom from './components/reactstrapcom' function App() { return ( <div className="data-table-block"> <Reactstrapcom name={123} /> </div> ); } export default App;
import React from 'react' import PropTypes from 'prop-types'; const Reactstrapcom = props => { return ( <h1>Props type checking -- {props.name}</h1> ) } export default Reactstrapcom Reactstrapcom.propTypes = { name: PropTypes.string.isRequired // optionalArray: PropTypes.array, // optionalBool: PropTypes.bool, // optionalFunc: PropTypes.func, // optionalNumber: PropTypes.number, // optionalObject: PropTypes.object, // optionalString: PropTypes.string, // optionalSymbol: PropTypes.symbol, };
Here, it will give console error because here name parameter in pass number not string and prop types check the name is a string.
It will give an error like below.
If you give name props in a string like below.
import './App.css'; import React from 'react' import Reactstrapcom from './components/reactstrapcom' function App() { return ( <div className="data-table-block"> <Reactstrapcom name={"Hello"0} /> </div> ); } export default App;
Here, not give the error you can see below.