Have you ever been annoyed with dynamic typic in JavaScript and all of the runtime errors that tend to follow it? If you said yes then you should consider using PropTypes in your application.

PropTypes

PropTypes is providing a bunch of validators that help you make sure that your props are of the expected types. If they are not then you’ll see errors appear in your browser console. Let’s take a look at an example.

import PropTypes from 'prop-types';

const User = ({ name, surname, age }) => {
  return (
    <div>
	<p>Name: {name}</p>
	<p>Surname: {surname}</p>
	<p>Age: {age}</p>
    </div>
  )
}

export default User

User.propTypes = {
  name: PropTypes.string,
  surname: PropTypes.string,
  age: PropTypes.number
};

We have written a User component that expects 3 props: name, surname and age. We’re then rendering those props in the relevant places to display some information about the user.

We have also used PropTypes to validate that we’re providing the props of the relevant type. We expect name and surname to be of type string and age to be of type number. Let’s move to App.js to see how to use our new component.

import User from './User'

function App() {
  return (
    <div style={{ margin: '50px' }}>
      <h1>Current User:</h1>
      <User name="Tommy" surname="Smith" age={23} />
    </div>
  );
}

export default App;

In App.js we’re simply using the User in the JSX and passing relevant props. Let’s see what our application looks like.

Well done! Looks like everything works as it should. There are no errors.

What if we made a mistake when passing props and swapped age and surname because we weren’t paying attention.

import User from './User'

function App() {
  return (
    <div style={{ margin: '50px' }}>
      <h1>Current User:</h1>
      <User name="Tommy" surname={23} age="Smith" />
    </div>
  );
}

export default App;

We can see that PropTypes detected that we passed the wrong props and threw a warning to the console. We can now easily debug it!

👋 Hey, I'm Dawid Budaszewski
Hello! I'm Dawid. I'm a full-stack developer with a couple of years of experience under my belt. I spent most of my career working with React. Now it's time to pass the knowledge onto somebody else!

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.