reactjs|June 27, 2020|3 min read

ReactJS - How to restrict data type for different kind of data

TL;DR

Use the prop-types library to define expected data types for component props (string, number, array, object) and mark required fields, enabling runtime type checking in React.

ReactJS - How to restrict data type for different kind of data

Introduction

Javascript is not a strict type language. We can use a variable to save any kind of data. Whether its a string or integer or boolean or object. Well, this gives aa flexibility in using the variabales. But, it brings some complexity of making sure that the data is of certain expected type only.

For example, you are showing data of students as:

  • Id
  • Name
  • Image
  • Age

Example reactjs component:

import React, { Component } from "react";

const Student = ({ name, age, img }) => {
  return (
    <article>
      <img src={img} alt="student" />
      <h5>name : {name}</h5>
      <h5>age : {age}</h5>
    </article>
  );
};

class StudentList extends Component {
  state = {
    students: [
      {
        id: 1,
        img: "some img path",
        name: "Raman",
        age: 21
      },
      {
        id: 2,
        img: "Some image path",
        name: "Rahul",
        age: 22
      }
    ]
  };
  render() {
    return (
      <section>
        {this.state.students.map(student => (
          <Student
            key={student.id}
            img={student.img}
            name={student.name}
            age={student.age}
          />
        ))}
      </section>
    );
  }
}

class App extends Component {
  render() {
    return <StudentList />;
  }
}

export default App;

If you messed up somewhere in your data. You might ends up showing age in place of name, or name in place of age. Since, there will be no error or warning unless you are doing some special operation with that variable.

Lets discuss abaout making our type strict.

Prop Types

There is a npm module for this purpose: prop-types. To install this module:

npm install prop-types

How to use

Lets see the modified component:

import React, { Component } from "react";
import PropTypes from "prop-types";

const Student = ({ name, age, img }) => {
  return (
    <article>
      <img src={img} alt="student" />
      <h5>name : {name}</h5>
      <h5>age : {age}</h5>
    </article>
  );
};
Student.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  img: PropTypes.string
};

class StudentList extends Component {
  state = {
    students: [
      {
        id: 1,
        img: "some img path",
        name: "Raman",
        age: 21
      },
      {
        id: 2,
        img: "Some image path",
        name: "Rahul",
        age: 22
      }
    ]
  };
  render() {
    return (
      <section>
        {this.state.students.map(student => (
          <Student
            key={student.id}
            img={student.img}
            name={student.name}
            age={student.age}
          />
        ))}
      </section>
    );
  }
}

class App extends Component {
  render() {
    return <StudentList />;
  }
}

export default App;

Notice the usage of propTypes aasa:

Student.propTypes

We are declaring the data types of certain type of data. And, if we try to provide any other kind of data to such variables, react will complain. It will throw errors. And you will come to know the mistakes.

How to restrict data to be Required (Not Null)

In many scenarios we would require that the data not be null. With prop-types you can specify or restrict with some attributes that this particular data must be present.

Lets see how to do this:

Student.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  img: PropTypes.string
};

Note: Above code will work if you are receiving your values as individual fields. If you are receiving the object, above code will not work. For objects, we have a slightly different way:

Student.propTypes = {
  student: PropTypes.shape({
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired,
    img: PropTypes.string
  })
};

In above code, we have decided that name and age must be present. If our data does not have these fields, then we will get errors.

How to configure default properties

In many cases, our data does not have some of the attributes. Example: Image is not there. And we would want to declare some default values. It means, if our data does not have any value for particular attribute, please use this default value.

Student.defaultProps = {
  img: "some default image path"
};

prop-types does not support Objects for default values.

Related Posts

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous setState() method in ReactJS class components…

ReactJS - Basic Form Handling and Form submission

ReactJS - Basic Form Handling and Form submission

Introduction Lets take a look at how forms are being handled in ReactJS. We will…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - How to pass method to component and how to pass arguments to method

ReactJS - How to pass method to component and how to pass arguments to method

Introduction In the ReactJS project, you are having aa parent component and a…

ReactJS - 3 ways to Import components in ReactJS

ReactJS - 3 ways to Import components in ReactJS

Introduction In this post, we will discuss 3 different ways to import a…

ReactJS - How to use conditionals in render JSX

ReactJS - How to use conditionals in render JSX

Introduction In this post, I will show several ways to use conditionals while…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…