Props types in React js
we had noticed that we use props quite a bit in our components. For the most part, we'll expect these to be a particular type or set of types (aka an object or a string ). React provides a method for defining and validating these types that allow us to easily expose a component API.
The prop-types object exports a bunch of different types which we can use to define what type a component's prop should be. We can define these using the propTypes method in the ES6 class-style React prop:
1class Clock extends React.Component {
2 // ...
3}
4Clock.propTypes = {
5 // key is the name of the prop and
6 // value is the PropType
7}
8
First, we'll need to import the PropTypes object from the prop-types package using the import keyword again:
1import PropTypes from 'prop-types'
You can also use the PropTypes object directly in your browser by adding the following script tag in your page
1https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.8.1/prop-types.min.js
Basic types
React exposes a few basic types we can use out of the box.
1Clock.propTypes = {
2 title: PropTypes.string, // 'hello'
3 count: PropTypes.number, //10, 0.1
4 isOn: PropTypes.bool, // true / false
5 onDisplay: PropTypes.func,//const say => (msg) => console.log("Helloworld")
6
7 symbol: PropTypes.symbol,// Symbol("msg")
8 user: PropTypes.object,//{name: 'Ari'}
9 name: PropTypes.node//'whatever', 10, {}
10}
Requiring types
It's possible to require a prop to be passed to a component by appending any of the proptype descriptions with .isRequired :
1Clock.propTypes = {
2 title: PropTypes.name.isRequired,
3}
Custom types
Finally, it's also possible to pass a function to define custom types. We can do this for a single prop or to validate arrays. The one requirement for the custom function is that if the validation does not pass, it expects we'll return an Error object:
1UserLink.propTypes = {
2 userWithName: (props, propName, componentName) => {
3 if (!props[propName] || !props[propName].name) {
4 return new Error(
5 "Invalid " + propName + ": No name property defined for
6component " + componentName
7 )
8 }
9 }
10}
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: