The prop-types library in React is used to validate the types of props or properties passed to components. It helps to catch bugs and ensure correct data types during development. It can validate a wide range of prop types such as strings, numbers, arrays, functions, objects, and even custom validations like checking a value meets a certain condition.
Let me explain it with an example.
Following step-by-step procedure helps you to build an application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘component-property-types-validation’
Project structure looks like below.
Step 2: Install prop-types dependency.
Add the prop-types dependency to the package.json file
"prop-types": "^15.8.1"
The caret (^) in front of the version number means that npm can automatically install newer versions of prop-types, as long as they are compatible with version 15.x.x.
After editing the package.json, go to the location where package.json located and run the following command to install the dependencies.
npm install
Step 3: Define UserDetails component.
Create components folder in src/ folder and dfine UserDetails component.
UserDetails.jsx
import PropTypes from "prop-types";
export default function UserDetails(props) {
return (
<div>
<h1>User Information</h1>
<ul>
<li>Username : {props.username}</li>
<li>Email : {props.email}</li>
<li>Age : {props.age}</li>
</ul>
<h1>User Hobbies</h1>
<ul>
{props.hobbies.map((hobby, index) => (
<li key={index}>{hobby}</li>
))}
</ul>
</div>
);
}
UserDetails.propTypes = {
username: PropTypes.string.isRequired, // name must be a string and required
age: PropTypes.number.isRequired, // age must be a number and required
email: PropTypes.string, // email must be a string and required
hobbies: PropTypes.arrayOf(PropTypes.string).isRequired, // hobbies must be an array of strings
};
Step 4: Update main.jsx file with below content.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UserDetails from './components/UserDetails'
const userDetails = {
"username" : "Chamundeswari",
"email" : "chamu@example.com",
"hobbies" : [
"Trekking",
"Cooking"
]
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<UserDetails {... userDetails}/>
</StrictMode>,
)
Step 5: Build and run the application by executing below commands.
cd component-property-types-validation npm install npm run dev
Open the url 'http://localhost:5173/' in the browser (Open inspect panel before opening this url).
As you see, we are not passed the value to age property for the UserDetail component. In the inspect panel, you can see the same warning.
You can download this application from this link.
No comments:
Post a Comment