React Proptype Array With Shape

Oluwafisayo Oluwatayo Oct 12, 2023
  1. PropTypes Shape in React
  2. Conclusion
React Proptype Array With Shape

Coding on React is a pleasant exercise until one deploys an app and the app fails because of errors and bugs.

Thankfully we have React’s proptype dependency to bail us out. Props in React are short for properties, and there are different props in React: number, strings, Boolean, object, etc.

What proptype does is that it checks the type of props we are passing in our codes to ensure that it is the right one; when we pass a wrong one, the proptype alerts through the browser’s console.

PropTypes Shape in React

The PropTypes.Shape() offers a deeper level of type-checking and validation; it scans through the inner structure of an array for wrong props.

To use this feature, we need to install it inside the project folder we are working on by typing in: npm i prop-types. When the installation is finished, then we go to the coding part.

Let us look at an example that shows the PropTypes.shape() in action.

Inside the src folder, we will create a new file, name it Component.js, navigate to the file, and import the proptypes, as seen below.

Code Snippet - Component.js:

import PropTypes from 'prop-types'

function Component() {
  return null
}

Component.propTypes = {
  person: PropTypes.shape({
    name: PropTypes.string,
    age: PropTypes.number,
  })
}

export default Component;

Since we want the proptypes to check out the string and number props of the date we want to render in the App.js, we wrap the name and age components inside the PropTypes.shape.

Next, we navigate to the App.js file and import the Component.js file like below.

Code Snippet - App.js:

import Component from './Component'

function App() {
  return < Component person = {
    {
      name: 'Kyle', age: '26'
    }
  } />
}

export default App

Output:

PropTypes Shape in React sample

If we open the browser’s console, we see the error in the attached screenshot because the age prop is passed as a string instead of a number. Once this anomaly is corrected, the error log disappears.

This is the awesomeness of utilizing the proptype dependency.

Conclusion

The effectiveness of the PropTypes cannot be overestimated because it is great for detecting errors and bugs on the spot. It helps us write more accurate and well-structured codes.

Oluwafisayo Oluwatayo avatar Oluwafisayo Oluwatayo avatar

Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.

LinkedIn