{

React model class example


This post covers an step by step tutorial on how to add model class

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

React is front end UI framework, It is based on components takes input from user and send it to Database as well displays the data to 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 classes with ES6 onwards You can check model class example in Angular application.

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

How to create a model class in React javascript application

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

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

Let’s add properties id, name to model class

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

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

In order 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 an javascript class objects.

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

  • In render, retrieve the data from state and iterate using array map and display in 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 more powerfull keyword for creating classes.

We can use interface or class keyword to create an 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 import keyword

  • Created array of model class objects, store this in a variable
  • store this in react state object
  • Read and display in react component using 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 an data validation
  • These are available at compilation/transpilation stage only, and will not be available in production
  • Interface defines the what type data holds but not able to create a 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 onw 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 class keyword, In typescript react component, I will also start with interface for type checking , if there is 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.





Related posts

Top 6 In operator examples in Javascript|Typescript|Angular

How to populate enum object data in dropdown in angular| Angular material dropdown example

Best Ways to convert timestamp to Date format in typescript| Angular timestamp date example

How to compare dates in Angular | Momentjs example

Different ways to write a comments in Typescript| Angular Component Comment example

Multiple ways to download an file or image from a Javascript?

How to set focus on top page in angular|javascript example