Typechecking With React PropTypes

Let’s validate your props

What is React PropTypes?

PropTypes are a feature for runtime validation of props during development.

Why use React PropTypes?

Sorry, not his type.
import React, { Component } from "react";
import PersonGreeter from "./PersonGreeter";
class App extends Component {
state = {
persons: [
{ id: 1, name: "Steven", age: 27 },
{ id: 2, name: "John", age: 2 },
{ id: 3, name: "Smith", age: 8 }
],
clicked: false
};
clickHandler = () => {
this.setState({ clicked: !this.state.clicked });
};
mapThroughPersonsArray = () => {
return this.state.persons.map((person, index) => (
<PersonGreeter
key={person.id}
person={person}
name={person.name}
age={person.age}
clicked={() => this.removePersonHandler(index)}
/>
));
};
removePersonHandler = personIndex => {
const persons = [...this.state.persons];
persons.splice(personIndex, 1);
this.setState({ persons: persons });
};
render() {
return (
<div className="app_heading">
<h1>Welcome to Person Greeter!</h1>
<button className="showButton" onClick={this.clickHandler}>
Show Persons
</button>
{this.state.clicked && this.mapThroughPersonsArray()}
</div>
);
}
}
export default App;

Setting up PropTypes and How to use

npm intall --save prop-types
import PropTypes from 'prop-types'
PersonGreeter.propTypes = {};
Setting up our React propTypes in our component
Prop Validation in the Console

And that’s Typechecking with React PropTypes!

More with PropTypes

Console logging PropTypes gives you a list of validators
//Class componentList.PropTypes = {
todos: PropTypes.array.isRequired,
};
//Instance of propType (In a functional component)List.propTypes = {
todos: PropTypes.array.isRequired,
};

--

--

--

Software Engineer , Flatiron school — Access Labs graduate. Born and raised New Yorker, latino from the Bronx.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Remove nth to Last Element in a Linked List (Javascript)

Configuring tailwindcss for Rails 6 with webpacker

GTM Tracking Service in Angular

14 Features That Make Angular My First Choice Front End Framework

Migrating to CSS in JS: Part 1

Photo of a flock of birds flying under blue sky during daytime

Create Refs dynamically in React

Mr Krabs Link

Calculating in React

[Notice] Klaytn SDK (caver-js, caver-java) v1.5.7 Released

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Steven Paulino

Steven Paulino

Software Engineer , Flatiron school — Access Labs graduate. Born and raised New Yorker, latino from the Bronx.

More from Medium

How & when to use redux in react projects?

React Forms and How To Control Them

Form Handling in ReactJS & Typescript with Custom Hooks

React 18 , what’s new ?