Prop Types In React JS

In This Blog, you are going to learn prop types with function components in react js, prop types is used for type checking of props which is very useful to validate the data in react app.

Prop Types In React

React JS PropTypes

  • In React JS, props, which stand for “properties”, pass data from one component to another.
  • In React JS, If a component receives the wrong type of props, it can lead to bugs and unexpected errors in your app.
  • As we all know that, JavaScript does not have a built-in type-checking solution, many developers use extensions such as TypeScript and Flow.
  • However, React has an internal mechanism for props validation called prop types (type checking).
  • In React JS, We pass different types of information, such as integers, strings, arrays, etc., as props to the components.
  • In React JS, we can either create default props or pass the props directly as attributes of the components.
  • In React JS, we passed props from outside a component and used them inside that component.
  • But did we have to check what kind of values we are getting inside our component via props.
  • Before React 15.5.0, proptypes are available in the React package, but in later versions of React, you need to add a dependency to your project.

Wide Range Of Validators

  • PropTypes.array,
  • PropTypes.bool,
  • PropTypes.func,
  • PropTypes.number,
  • PropTypes.object,
  • PropTypes.string,
  • PropTypes.symbol,

App.js File – Code

import logo from './logo.svg';
import './App.css';
import PropTypes from 'prop-types';

function App(props) {
  return (
   <h1>Hey {}</h1>
   <h1>Hey {props.age}</h1>
   <h1>Hey {props.isMarried.toString()}</h1>
   <h1>Hey {String(props.isMarried)}</h1>

App.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  isMarried: PropTypes.bool,
  arr: PropTypes.array
App.defaultProps = {
  name: 'Anonymous',
  age: 18

export default App;

Index.js File – Code

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
const friends = ["Amit","Zain","Kumar","Ali"];
    <App isMarried={false} arr={friends}/>

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:

Click Below Link to Download Notes & Source Code Of This Blog

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *