Blog>
Snippets

Typechecking with PropTypes

Illustrate how to use PropTypes to ensure that components receive props of the correct type.
import PropTypes from 'prop-types';
Import the PropTypes library, which is necessary for typechecking props.
const UserProfile = ({ name, age, hobbies }) => (
  // Component that uses name, age and hobbies props
  <div>
    <h1>{name}</h1>
    <p>Age: {age}</p>
    <ul>
      {hobbies.map(hobby => <li key={hobby}>{hobby}</li>)}
    </ul>
  </div>
);
Define a functional component called 'UserProfile' that takes 'name', 'age', and 'hobbies' as props.
UserProfile.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  hobbies: PropTypes.arrayOf(PropTypes.string)
};
Use the PropTypes library to set the expected types for the UserProfile component's props. The 'name' and 'age' props are marked as required, while 'hobbies' is an optional array of strings.
const App = () => (
  <UserProfile 
    name={'Jane Doe'} 
    age={30} 
    hobbies={['reading', 'gaming', 'hiking']} 
  />
);
Create an 'App' component that renders the 'UserProfile' component with correct prop types.