{

React model class example


This post covers a step-by-step tutorial on how to add a model class in React App.

  • How to create a model class in react application
  • When to use class or interfaces for models in Angular applications?
  • Initialize model class with an array of objects in react application
  • Display model classes data in react render function.

React is a front-end UI framework. It is based on components that take input from the user and send it to the Database as well as display the data to the browser.

To make it interactive between frontend and backend, Model classes are helpful to simplify the communication.

Model classes can be of type interface or classes in typescript, But in javascript, We can only create a class with ES6 onwards. You can check model class example in Angular application.

Model classes are simple attributes or properties of an object which hold the information of an entity.

How to create a model class in React javascript application

For example, Let’s create an Employee class in the ES6 class keyword

filename is Employee.js We created Employee.js javascript file in src/model

Let’s add properties id, name to model class

You can add a setter or getter or constructor to initialize the properties during object creation.

export class Employee{
    constructor(id,name) {
      this.id = id;
      this.name = name;
    }
  }

To use this class, You have to import in react application

import { Employee } from './Employee';

Next, How do you create an object of a class and use it in react app.

  • In the below example, Created a custom component

  • Added constructor with default state storing array of employee objects

  • In Real applications, Data is coming from REST API as a javascript class object.

  • Now, the Array of objects are stored in react state object

  • In render, retrieve the data from state and iterate using array map and display in an ordered list.

    Here is an example react code

import React from 'react';
import './style.css';
import { Employee } from './Employee';
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      emps: [new Employee(1, 'John'), new Employee(2, 'Ram'),new Employee(3, 'Franc')]
    };


  }
  render() {
    const listItems = this.state.emps.map((item) => <li key={item.id}>{item.name}</li>);

    return (<ul>{listItems}</ul>);
  }
}
export default App;

React model class example in typescript

In typescript react applications, We have a more powerful keyword for creating classes.

We can use the interface or class keyword to create a model class

Let’s create an model class with interface keyword

export class Employee {
  private id: number;
  private firstName: string;
  private lastName: string;
  private salary: number;

  constructor(id: number, firstName: string, lastName, salary: number) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
  }

  getName(): string {
    return `${this.firstName} ${this.lastName}`;
  }

  getYearlySalary(): number {
    return 12 * this.salary;
  }
}

Create a react typescript component.

In react typescript component, You have to load using the import keyword

  • A created array of model class objects, store this in a variable
  • store this in react state object
  • Read and display in react component using the array map function

React model interface example

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import { Employee } from './Employee';

interface AppProps {}
interface AppState {
  name: string;
}

class App extends Component<AppProps, AppState> {
  employees: Employee[] = [
    new Employee(1, 'john', 'sedwik', 5000),
    new Employee(2, 'Ram', 'Kumar', 6000),
    new Employee(3, 'Fran', 'andrew', 10000)
  ];
  constructor(props) {
    super(props);
    this.state = {
      data: this.employees
    };
  }

  render() {
    const emps = this.state.data;
    console.log(emps)
    let result = emps.map(item => <li key={item.id}>{item.firstName}-{item.salary}</li>);

    return (
      <div>
        <ul>{result}</ul>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

When to use class or interface for models in React application?

interface in typescript

  • Interfaces helps code type checking of a data validation
  • These are available at the compilation/transpilation stage only, and will not be available in production
  • Interface defines what type of data holds but is not able to create an instance an interface
  • There are no methods to deal with how to add/get manipulation
  • Typescript is compiled to javascript at runtime, hence, These are not available in javascript.

Class in typescript

  • Classes are available in javascript/typescript from ES6 on version only.
  • This also helps to do type checking
  • This will be available and generates classes code during compilation/transpilation
  • You can add custom methods or setter/getter or constructor for data manipulation

Conclusion

In Summary, We can either create a class or interface in react application for holding model data. In javascript, We can only use the class keyword, In the typescript react component, I will also start with an interface for type checking, if there are any data manipulation methods, Convert the interface to class and use it in react application.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.