DEV Community

Shubham Pandey
Shubham Pandey

Posted on

2 1

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.😁

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay