0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Props Validation Using Prop Types

Posted at

Introduction:

In React, props (short for “properties”) are used to pass data from one component to another, usually from a parent to a child component. However, as applications grow, managing the types and structures of props becomes crucial to prevent bugs and ensure components receive the correct data.

One of the important features of React uses a component-based architecture system. Components take data through the use of props and make it more reusable and flexible.

In this article, we will explore React props Validation using the prop types with practical examples and how to pass data from the parent to the child component.

Reactt.jpg

Props in React:

Props are a way of passing data from a parent component to a child component in React. They make components reusable and dynamic by allowing customization through external data.

Basically, it allows you to pass the data from one component to another. It ensures data integrity, improves code reusability, and also readability. This is similar works as the HTML attributes that store the dynamic data.

Example

Code:

import React from "react";
function Data(props) {
  return (
    <div>
      <h2>User Name: {props.name}</h2>
      <p>Country: {props.country}</p>
      <p>Company: {props.company}</p>
      <p>Project: {props.project}</p>
      <p>Email: {props.email}</p>
    </div>
  );
}
function App() {
  return (
    <div>
      <h1>Tech Client Detail</h1>
      <Data
        name="Tpoint tech"
        country="London"
        company="Tpt software ltd."
        project="Learning Management System"
        email="Tp2453@gmail.com"
      />
    </div>
  );
}
export default App;

Output:

Tech Client Detail
User Name: Tpoint tech
Country: London
Company: Tpt software ltd.
Project: Learning Management System
Email: Tp2453@gmail.com

How React props Work?

React props help to pass the data to the component, such as functions, Arrays, objects, strings, or numbers etc. Only props are sending data from parent to child component, but state is sending data within the component. It uses the unidirectional data flow, which means only parent to the child side.

Why use the validate props in React?

If you are creating an application, you need to manage the props, remove errors, and bugs. It can be easily built up to make your component more readable and predictable.

Here are some points that describe why use validate props in React:

1) Improve Code readability:

Props are used to build up your code to be self-documenting. It helps to make code more readable, maintainable, debug, and also update React components.

Syntax:

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  isFree: PropTypes.bool,
};

2) Prevents the Bugs:

It validates that the component should be taken as the correct data format. Props help for avoiding bugs such as missing data types, props, or managing rendering issues.

Syntax:

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
};

3) Error Detection and debugging:

It stores a built-in system in React to detect errors. If the developers send incorrect data to your component, it shows a warning in the console. Such as Warning: Failed prop type: Invalid prop age of type string supplied to UserInfo, expected number.

Example

Code:

import React from "react";
import PropTypes from "prop-types";
function Greeting(props) {
  return (
    <div>
      <h2>Hello, {props.name}!</h2>
      <p>Age: {props.age}</p>
    </div>
  );
}
Greeting.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
};
function App() {
  return (
    <div>
      <Greeting name="Tpoint tech" age={19} />
    </div>
  );
}
export default App;

PropTypes in React

PropTypes is a React mechanism to validate the component of props. Components use the propTypes property to verify the type. It finds that the props are using this data type, like number, array, string, object, etc.

It works as the type-checking safety net for your React components.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
function Message({ text, count }) {
  return (
    <div>
      <h3>{text}</h3>
      <p>You have {count} new messages.</p>
    </div>
  );
}
Message.propTypes = {
  text: PropTypes.string.isRequired, 
  count: PropTypes.number,           
};

Message.defaultProps = {
  count: 0,
};
function App() {
  return (
    <div>
      <Message text="Hello, TPoint tech!" count={5} />
      <Message text="Welcome Back!" /> 
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

Why use PropTypes in React?

1) Manage Code Clarity:

It can be easily managed to include the propTypes, including data types, and also props in the form of documentation of the components.

2) Error Detection:

This helps catch type-related bugs in development. If your component takes a prop with an invalid data type, show the warning message in the console.

3) Data integrity:

With the prop types validation, you can check that the component takes the correct type of data. It prevents the re-rendering issue.

How to use the prop-types library in React?

Before the React 15 version, it was also known as PropTypes and worked as a React package. After coming, this provides more validations for managing the component props. You can use React.PropTypes.

You can add some dependencies in the project for setup, such as

npm install prop-types

For a ReactJS project, import files such as

import PropTypes from 'prop-types';

Commonly used PropTypes Validators

PropTypes provides a huge range of validators for managing the type of definitions.

Here are some of the Validator’s explanations:

• PropTypes.array: It checks that the prop is an array
• PropTypes.string: It checks that the prop is an string
• PropTypes.object: It validates that the prop is an Object
• PropTypes.number: It checks that the prop is a number
• PropTypes.func: It validates that the props is a function
• PropTypes.bool: It validates that the props is a Boolean
• PropTypes.symbol: It checks that the props is a JavaScript symbol

Practical Examples of PropTypes

1) Object and Array Validation:

Example

Code:

import React from "react";
import PropTypes from "prop-types";
function NumberList({ nums }) {
  return (
    <ul>
      {nums.map((num, index) => (
        <li key={index}>{num}</li>
      ))}
    </ul>
  );
}
NumList.propTypes = {
  nums: PropTypes.arrayOf(PropTypes.num).isRequired, 
};
NumList.defaultProps = {
  nums: [],
};
export default NumberList;

2) Simple Validation:

Example

Code:

import React from "react";
import PropTypes from "prop-types";
function UserProfile({ username, age, email, isMember, hobbies }) {
  return (
    <div>
      <h2>{username}</h2>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
      <p>Status: {isMember ? "Active Member" : "Guest"}</p>
      <p>Hobbies:</p>
      <ul>
        {hobbies.map((hobby, index) => (
          <li key={index}>{hobby}</li>
        ))}
      </ul>
    </div>
  );
}
UserProfile.propTypes = {
  username: PropTypes.string.isRequired,        
  age: PropTypes.number.isRequired,             
  email: PropTypes.string,                       
  isMember: PropTypes.bool,                      
  hobbies: PropTypes.arrayOf(PropTypes.string),  
};
UserProfile.defaultProps = {
  email: "Not provided",
  isMember: false,
  hobbies: ["No hobbies listed"],
};
export default UserProfile;

3) Custom Validator function:

Example

Code:

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
function Score({ score }) {
  return <h4>Your score is {score}</h4>;
}
Score.propTypes = {
  score: function (props, propName, componentName) {
    const value = props[propName];
    if (typeof value !== "number") {
      return new Error(
        `Invalid prop \`${propName}\` supplied to \`${componentName}\`. Must be a number.`
      );
    }
    if (value < 0 || value > 50) {
      return new Error(
        `Invalid prop \`${propName}\` supplied to \`${componentName}\`. Score must be between 0 and 50.`
      );
    }
  },
};
Score.defaultProps = {
  score: 0,
};
function App() {
  return (
    <div>
      <h1>Score Checker</h1>
      <Score score={25} /> 
      <Score score={55} /> 
      <Score />             
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

Conclusion:

I hope this article provides you a strong explanation of React props Validation Using PropTypes for all levels of developers. With the use of props in prop types, you can avoid bugs and errors, and also validate your props. It enhances the code readability, maintainability, and reliability, mainly used in large applications to interact with one or more components.

For a detailed and clear understanding of ReactJS, Tpoint Tech provides React tutorials, all related concepts, and interview questions as well.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?