react js contact with backend api and display data in component

Updated: Feb 14, 2025

react js contact with backend api and display data in component

To contact a backend API and display data in a React JS component, follow these steps:

  1. Set up your project: First, make sure you have a React project set up. You can create a new project using Create React App or use an existing one.

  2. Install necessary packages: To make HTTP requests, you can use axios or fetch. Install one of these packages using npm or yarn:

    npm install axios
    # or
    yarn add axios
    
  3. Create a new component: Create a new component where you want to display the data fetched from the API. Let's call it DataComponent.js.

  4. Fetch data from the API: In the componentDidMount() lifecycle method, use the installed package to fetch data from the API. Here's an example using axios:

    import React, { Component } from 'react';
    import axios from 'axios';
    
    class DataComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          loading: true
        };
      }
    
      componentDidMount() {
        axios.get('https://your-api-url.com/data')
          .then(response => {
            this.setState({ data: response.data, loading: false });
          })
          .catch(error => {
            console.log(error);
            this.setState({ loading: false });
          });
      }
    
      render() {
        // render your component here
      }
    }
    
    export default DataComponent;
    

    Replace 'https://your-api-url.com/data' with the actual API URL and replace response.data with the expected data format.

  5. Render data in the component: In the render() method, use the fetched data to render the component. Here's an example:

    render() {
      return (
        <div>
          {this.state.loading && <p>Loading...</p>}
          {this.state.data.map(item => (
            <div key={item.id}>
              <h2>{item.title}</h2>
              <p>{item.description}</p>
            </div>
          ))}
        </div>
      );
    }
    

    Replace <h2>{item.title}</h2> and <p>{item.description}</p> with the actual HTML structure you want to use for each data item.

  6. Use the component: Finally, use the DataComponent in your app by importing it and rendering it in a JSX file:

    import React from 'react';
    import DataComponent from './DataComponent';
    
    function App() {
      return (
        <div className="App">
          <DataComponent />
        </div>
      );
    }
    
    export default App;
    

Now, when you run your app, it should fetch data from the API and display it in the DataComponent.