Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How React handle or restrict Props to certain types, or require certain Props to exist ?

  • Last Updated : 25 Oct, 2021

React allows us to pass data from parent component to child components with the help of props. If we want to check the type of props we can do so with the help of PropTypes. Proptypes helps us to perform runtime type checks on the props and if the check fails we get a warning on the browser’s console. 

Syntax:

import PropTypes from 'prop-types';
ComponentName.propTypes = {
  // type checks
};

If we want to restrict a prop to the string type we can do it using the syntax mentioned below.

import PropTypes from 'prop-types';
ComponentName.propTypes = {
  name: PropTypes.string
};

If we want to make a prop with any data type then we can do it using the syntax mentioned below.

import PropTypes from 'prop-types';
ComponentName.propTypes = {
  name: PropTypes.any.isRequired
};

 



Project Setup:

Step 1: Create a new react project using the following command on the command line.

npx create-react-app name_of_the_project

Step 2: Create a new file named Info.js inside the src directory of this project.

Project Structure: After following the steps the project structure should look like.

In the app.js file, the App component consists only of Info as the child component. We pass two props to the Info component that names which is a Number type and username which is of String type.

App.js




import Info from './Info';
  
const App = () => {
  return <Info name={1} username={'gfg@123'} />;
};
  
export default App;

In the Info.js file, we create the Info functional component which receives props. Using the Prop types we apply type checks that is name prop can only be of type string and username prop can only be of type string as well it is required i.e., it is compulsory to pass username prop to Info component otherwise we will get a warning in the browser console. 

Info.js




import PropTypes from 'prop-types';
  
const Info = (props) => {
  return (
    <div>
      <div>Name: {props.name}</div>
      <div>Username: {props.username}</div>
    </div>
  );
};
  
Info.propTypes = {
  name: PropTypes.string,
  username: PropTypes.string.isRequired,
};
  
export default Info;

Step to run the application: To start your application, use the following command on the command line.

npm start

Output: Open the browser and go to http://localhost:3000, you will see the following output.

Explanation: Inside the Info.js file, we restricted the name prop to string type with the help of PropTypes but from the App component, we passed a number type (i.e., 1) as a value to the name prop. This is why we get a warning in the browser console saying the value of the name was expected to be of type string but a number was received.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!