Type checking in React

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>; } }

How we can manage this problem ?

defaultProps

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

propTypes

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

Calculator.propTypes = { number1: PropTypes.number.isRequired, number2: PropTypes.number.isRequired }; Using defaultProps and propTypes we can avoid alot bugs, errors and mistakes , because we can see the validations messages in the browser console.

Validation Messages

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