AppDividend
Latest Code Tutorials

How To Add And Display Data In React 16 Example

0

One of the essential things you can do with a UI is to display some data. React makes it easy to display data and automatically keeps the interface up-to-date when the data changes. We will create a small application in which we can add a hotel card in the list with a button click and display that hotel card. In this example, I will use the React 16, which is right now the latest version of React.

How To Add And Display Data In React

Create a new React.js project using the create-react-app.

npx create-react-app reactx

Go inside the folder and open the project folder in Visual Studio Code.

Then install the Bootstrap 4 Framework.

yarn add bootstrap

Import the Bootstrap CSS file inside the src >> App.js file.

Write the following code inside the App.js file.

// App.js

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div className="container">
      Add and Display Data in React 16
    </div>
  );
}

export default App;

As you can see, we have imported bootstrap.min.css file.

React uses an XML-like syntax called JSX. React makes it painless to create interactive User Interfaces(UIs).

Using React, we can design simple views for each state in our application, and React will efficiently update and render just the right components when our data changes.

Declarative views make our code more predictable and easier to debug.

Create React components

Inside the src folder, create a new directory called components.

Inside that folder, create two components.

  1. HotelList.js
  2. HotelCard.js

We will create a HotelList.js as a class-based React Component because it deals with the state.

We will create HotelCard.js as a function component because it does not deal with any data.

Functional Component in React

The functional component is just a function that accepts props and returns a React element. But you can also use the ES6 syntax to write components.

Syntax

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

A functional component is just plain JavaScript function that accepts props as an argument and returns a React element.

Because it is just a JavaScript function, and you cannot use setState() in your component.

That’s the reason why they also get called functional stateless components. So every time you see a functional component, you can be sure that this particular component doesn’t have its state.

Class Component in React

A class component requires you to extend from React.Component and create a render function that returns a React element. 

Syntax

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

If you need the state in your component, you will either need to create a class component, or you lift the state to the parent component and pass it down the functional component via props.

Another feature that you cannot use in functional components is lifecycle hooks. The reason is the same as for state, and all lifecycle hooks are coming from the React.Component which you extend from in the class components.

So if you need lifecycle hooks, you should probably use a class component.

Now, let’s get back to our project.

Write the following code inside the HotelCard.js file.

// HotelCard.js

import React from 'react'

export function HotelCard() {
  return (
    <div className="col-md-3 col-xs-6">
      <div className="card">
        <img className="card-img-top" src="http://via.placeholder.com/350x250" alt=""></img>
        <div className="card-body">
          <p className="card-text">
            Taj Hotels is a chain of luxury hotels and a subsidiary of the Indian Hotels Company Limited; headquartered at Express Towers, Nariman Point in Mumbai. Incorporated by the founder of the Tata Group, Jamsetji Tata, in 1903, the company is a part of the Tata Group, one of India's largest business conglomerates.
          </p>
        </div>
      </div>
    </div>
  );
}

We have defined this component as a functional component because it does not have to deal with the state. It is a card component that we will display on the screen.

Create a Class Component

We have created the HotelCard.js component. Now, we need to create a HotelList.js component, which is the class-based component.

Write the following code inside the HotelList.js file.

// HotelList.js

import React, { Component } from 'react';
import { HotelCard } from '../components/HotelCard';

export class HotelList extends Component {

  constructor() {
    super();
    this.state = {
      hotels: [1, 1, 1]
    }
  }

  renderHotels() {
    return this.state.hotels.map((hotel, i) => (
      <HotelCard key={i} />
    ));
  }

  addHotelRoom() {
    const hotels = this.state.hotels;
    hotels.push(1);
    this.setState({
      hotels
    });
  }

  render() {
    return (
      <section>
        <div className="row">
          <div className="col-md-3">
            <h2 className='page-title'>Hotel Rooms</h2>
          </div>
          <div className="col-md-6">
            <button onClick={() => { this.addHotelRoom() }} className="btn btn-dark">Add Room</button>
          </div>
        </div>
        <div className='row'>
          {this.renderHotels()}
        </div>
      </section>
    )
  }
}

Let me explain the code here.

First, we have imported React and HotelCard component.

Then we have defined a constructor. When you define the constructor, you need to write the super() function because the class component extends the Component class of the react library. If you don’t write super() function, then you will get the error.

The next statement is setState() function.

React components can, and often do, have a state. The state can be anything.

The setState() function is the only legitimate way to update the state after the initial state setup.

Inside the setState() function, we have initialized the hotels’ array, which has 1, 1, 1 element.

Here, the array has hard-coded values, but in the real-life, the array has user-defined values that come from web forms.

Then we have defined the two functions.

renderHotels()

This function returns the HotelCard component. The function returns the no. of cards based on the length of the hotels’ array.

So, the renderHotels() function renders the hotel list.

addHotelRoom()

The addHotelRoom() function modifies the state and adds one element into the hotel array. If the user clicks the button, then 1 item will be pushed into the array and then render() function will render again and display one more HotelCard.

The last function is render() function. The render() function returns a JSX. If the state of the class is changed, then the render() function will re-render and display the data according to the modified state.

So, when the page is refreshed, it will first initialize the state and call the render() function.

Depend on the available data in the state, the render() function returns JSX.

Now, the last step is to import the HotelList.js component inside the App.js component.

// App.js

import React from 'react';
import { HotelList } from './components/HotelList';

import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div className="container">
      <HotelList />
    </div>
  );
}

export default App;

Save the file and start the React development server using the following command.

yarn start

See the output.

 

How To Add And Display Data In React 16

If you click on the Add Room button, then one card will be added on the screen.

If you want to interact with a backend server, then you can use the axios library for sending and receiving the network requests.

So, this is how you can add and display the data in React.js.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.