DEV Community

Shubham Pandey
Shubham Pandey

Posted on

React Type Checking

No Type checking -> Perk of using a dynamic language like Javascript.

But as your app grows, you start facing issues/bugs due to mishandling of type in props passed.

If you have nested prop passing boom 💥 .

Thankfully, React comes with built-in type checking abilities.

React uses prop-types library to implement type-checking.
Link

Usage

App.js

import React from "react"
import Cart from "./Cart"

function App() {
    return (
        <div>
            <Card price={400} title="Watch"}/>
            <Card price={600} title="Perfume"/>
            <Card price={1000} title="Mouse"/>
        </div>
    )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Here is a basic shopping cart example where each card represents single item with a title and a price.

Cart.js

import React from "react"
import PropTypes from "prop-types"

const Cart = (props) => {
  const { title, price } = props;
  return (
    <>
      <Card>
        <h2>{title}</h2>
        <h3>{price}</h3>
      </Card>
    </>
  );
};

Cart.propTypes = {
    title: PropTypes.string.isRequired,
    price: PropTypes.number
}

export default Cart

Enter fullscreen mode Exit fullscreen mode

PropTypes supports various validation and other handy code chunks.

Let's say we wanted our price to be one of 200,600,400

Cart.propTypes = {
    price: PropTypes.oneOf([200,300,400])
}
Enter fullscreen mode Exit fullscreen mode

Find other various use cases for PropTypes Link

Note:

  • Usage may vary as per your need but these are handy react-y way of type checks.😁

Top comments (0)