Open In App

React PropType Array with Shape

Last Updated : 10 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React PropType Array with Shape used to shape the given array data. It can apply custom user defined validation and validate the data accordingly when passes prop.

Prerequisites:

Approach:

To validate the given data as array we will use the React Prop Type with shape. We will defined custom shape to validate the given data using the PropType.shape method. It will create user defined validation to render and display only the validated data.

Steps to Create React Application:

Step 1: Create a React application using the following command:

npx create-react-app app-11

Step 2: After creating your project folder i.e. app-11, move to it using the following command:

cd app-11

Step 3: Run the development server:

npm start

Project structure:

Example: This example implement the proptype to render the courses details with defined validation for properties using proptype.shape method.

Javascript




// Filename - App.js
 
import Courses from "./Components/Courses";
 
function App() {
  let geekCourses = [
    {
      title: "App development with Java and Kotlin",
      price: 10000,
      duration: 5,
      mentor: "Aman Negi",
      TA: "Rahul Negi",
      classesPerWeek: 5,
    },
    {
      title: "Web development Nodejs",
      price: 9000,
      duration: 4,
      mentor: "Riya Rawat",
      TA: "Mihir Rawat",
      classesPerWeek: 4,
    },
    {
      title: "MERN stack ",
      price: 12000,
      duration: 6,
      mentor: "Kartik Sayana",
      TA: "Amogh Sayana",
      classesPerWeek: 6,
    },
    {
      title: "Machine Learning with python",
      price: 10000,
      duration: 6,
      mentor: "Rohit Jain",
      TA: "Utkarsh Jain",
      classesPerWeek: "5",
    },
  ];
  return (
    <div className="App">
      <Courses geekCourses={geekCourses} />
    </div>
  );
}
 
export default App;


Javascript




// Filename - Components/Courses.js
 
import React from "react";
import PropTypes from "prop-types";
 
const Courses = ({ geekCourses }) => {
    let displayCourses = geekCourses.map((course, idx) => {
        return (
            <div
                key={idx}
                style={{
                    border: "2px solid rgb(91, 222, 115)",
                    margin: "5px",
                    width: "30vw",
                    borderRadius: "10px",
                    boxShadow:
                        "5px 3px 11px -1px rgba(0,0,0,0.46)",
                    padding: "5px",
                }}
            >
                <h3> {course.title} </h3>
                <div
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                    }}
                >
                    <span style={{ margin: "5px" }}>
                        <strong>Duration:</strong>{" "}
                        {course.duration} days
                    </span>
 
                    <span style={{ margin: "5px" }}>
                        <strong>Price:</strong>{" "}
                        {course.price} Rs
                    </span>
                </div>
                <div
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                    }}
                >
                    <span style={{ margin: "5px" }}>
                        <strong>Mentor:</strong>{" "}
                        {course.mentor}
                    </span>
 
                    <span style={{ margin: "5px" }}>
                        <strong>TA:</strong> {course.TA}
                    </span>
                </div>
            </div>
        );
    });
    return (
        <div>
            Geeks Courses
            <div
                style={{
                    display: "flex",
                    flexWrap: "wrap",
                    padding: "5px",
                    justifyContent: "center",
                }}
            >
                {displayCourses}
            </div>
        </div>
    );
};
 
Courses.propTypes = {
    geekCourses: PropTypes.arrayOf(
        PropTypes.shape({
            title: PropTypes.string.isRequired,
            price: PropTypes.number.isRequired,
            duration: PropTypes.number.isRequired,
            mentor: PropTypes.string.isRequired,
            TA: PropTypes.string.isRequired,
            classesPerWeek: PropTypes.number.isRequired,
        })
    ).isRequired,
};
 
export default Courses;


Step to Run the Application: Use this command in the terminal inside project directory.

npm start

Output: Here is the output when there is no error in any object in the array.

Output when no type error

Explanation: Since we want to validate the type of geekCourses to be an array of objects so we use PropTypes.arrayOf property. Also we want to specify the object properties of the elements in the geekCoures array then we have to use PropTypes.shape inside the arrayOf property. We can also add isRequired property to make the individual object property to be present in the object, it will raise a warning if that property is not present in the object. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads