Module not found: Error: Can't resolve 'prop-types'

Updated at 15-Nov-2022, By samar

Module not found: Error: Can't resolve 'prop-types'

While working on my react app version 18.0.0, I was getting an error Module not found: Error: Can't resolve 'prop-types', Because prop-types has been removed from the react core package. You have to install the prop-types package using the npm install prop-types command in the terminal to get the solution for above error.

npm install prop-types

After installing the package using npm install prop-types command, I got the solution for above error in my react app.

If you are loading prop-types by script tag then you can use the below CDN link.

<script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
  • Example code of prop-types in React

    PropTypes are simply a mechanism that ensures that the passed value is of the correct data type. This makes sure that we don’t receive any errors at the very end of our react app.

    Before the release of React 15.5.0, PropTypes were available in the React package, but now we have to add the prop-types library in our project by npm install prop-types command.

    Before using the code snippet to understand the prop-types functionality in our react app we have to first install the prop-types package in react app using below command.

    npm install prop-types
    

    Example code

    Just paste the below code in index.js file under the src directory of react app and run the npm start command if you are not already running it.

    src\index.js

    import React from 'react';
    import * as ReactDOMClient from 'react-dom/client';
    import { PropTypes } from "prop-types";
     
    const Count = (props) => {
      return (
        <div className="app">
            <p>My name is {props.name} and my age is { props.age }</p>
        </div>
      )
    };
     
    Count.propTypes = {
        name: PropTypes.string,
        age: PropTypes.number,
    };
    
    const root = ReactDOMClient.createRoot(document.getElementById("root"));
    root.render(
        <Count name="samar" age={25}/>
    );
    

    In the above code snippet we have set prop type for name a string and for age a number. If You pass value of age with string data type like <Count name="samar" age="25"/> then you will get error Warning: Failed prop type: Invalid prop age of type string supplied to Count, expected number to avoid the error you have to pass value in number format to age like <Count name="samar" age={25}/>.

Back to code snippet queries related react