How to Add, Fetch and Display Data in React.js

Here are steps to dd and display data in React:

Step 1: Install 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 the bootstrap.min.css file.

React uses an XML-like syntax called JSX. As a result, react makes creating interactive User Interfaces(UIs) painless.

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.

Step 2: 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 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 data.

Functional Component

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.

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

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

Because it is just a JavaScript function, 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

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 must either create a class component or lift it to the parent component and pass it down to 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: all lifecycle hooks come from React.Component which you extend from in the class components.

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

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 functional because it does not have to deal with the state. It is a card component that we will display on the screen.

Step 3: 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>
    )
  }
}

renderHotels()

This function returns the HotelCard component. In addition, the function returns the no. of cards based on the length of the hotel’s array. The renderHotels() function renders the hotel list.

addHotelRoom()

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

The last function is the 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 initialize the state and call the render() function.

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

The last step is importing 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

One card will be added to the screen if you click the Add Room button.

If you want to interact with a backend server, you can use the axios library to send and receive network requests.

That’s it.

Leave a Comment

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