How to use React Type checking

September 22, 2018

The components in React allow receive data using Props, the props aren’t is strict, that’s mean you can send any type of value, or forget to send some value.

In our example, the component Calculator needs 2 props number1 and number2.

import React, { Component } from 'react';  export default class Calculator extends Component {  render() {  const { number1, number2 } = this.props;  let total = number1 + number2;  return ( <div> <input type="text" value={number1} />  <input type="text" value={number2} /> <span>{total}</span> </div> );  } }

We are sending a string value instead of a number and forget the second number.

import Calculator from './components/Calculator';  class App extends Component {  render() {  let edgar = 'The Wall'; return <div className="App">  <Calculator number1={edgar} /> </div>; }  }

Set a default props

It allows managing the default value for the props, in our component, the default value for number1 is 0 and this value can be overridden if number1 has value. Calculator.defaultProps = { number1: 0 };

import PropTypes

It gives us the easy way to set the type for each prop like string, number, function or mark as required as well.

import PropTypes from “prop-types”;

Calculator.propTypes = { number1: PropTypes.number.isRequired, number2: PropTypes.number.isRequired };

Using defaultProps and propTypes we can avoid a lot of bugs, errors, and mistakes because we can see the validations messages in the browser console.

Read more about the react type checking in https://reactjs.org/docs/typechecking-with-proptypes.html #react #js

Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.