DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on

How You Render Data From Backend In React ?

App.jsx

Image description

Import Statements

import React, { useEffect, useState } from "react";
import CardWrapper from "./card-wrapper";
import Card from "./card";
Enter fullscreen mode Exit fullscreen mode

React: The main React library for creating components.

useEffect: A hook that lets you perform side effects in function components (similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class components).

useState: A hook for adding state to function components.

CardWrapper and Card: Components imported from other files to be used within this App component.

Component Definition

const App = () => {
  const [photos, setPhotos] = useState([]);
  const [load, setLoad] = useState(false);
  const baseURL = "https://jsonplaceholder.typicode.com";
Enter fullscreen mode Exit fullscreen mode
  • App: A functional component.
  • photos and setPhotos: State variables initialized with an empty array. photos will store the fetched data, and setPhotos is the function to update it.
  • load and setLoad: State variables to manage the loading state. load is a boolean indicating whether the data has been loaded or not.
  • _baseURL: The base URL for the API endpoint._

Fetching Data with useEffect

  useEffect(() => {
    fetch(`${baseURL}/photos`).then((res) => {
      res.json().then((data) => {
        setPhotos(data);
        setLoad(true);
      });
    });
  }, []);
Enter fullscreen mode Exit fullscreen mode
  • useEffect: Hook that runs the fetch operation when the component mounts (empty dependency array [] means it runs only once).

  • fetch: Fetches data from the given API endpoint.

  • .then((res) => { res.json().then((data) => { ... }) }): Chains the promises. res.json() parses the JSON response._

  • setPhotos(data): Updates the photos state with the fetched data.

  • setLoad(true): Sets the loading state to true, indicating that data has been loaded.

Return to UI

  return (
    <div className="container">
      {
        load ? 
        <CardWrapper>
          {
            photos.length ?
            photos.map((item) => {
              return <Card key={item.id} state={item}/>
            })
            :
            <h1>Not found!</h1>
          }
        </CardWrapper>
        :
        <h1>Loading . . .</h1>
      }
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • The return statement defines the JSX to be rendered.
  • <div className="container">: A container div.
  • { load ? ... : <h1>Loading . . .</h1> }: Conditional rendering based on the load state.
  • If load is true:
  • <CardWrapper>: A wrapper component for the cards.
  • { photos.length ? ... : <h1>Not found!</h1> }: Nested conditional rendering.
  • If photos.length is not zero, map over the photos array and return a Card component for each item.
  • If photos.length is zero, render "Not found!".
  • If load is false, render "Loading . . .".

Export Statement

export default App;
Enter fullscreen mode Exit fullscreen mode
  • Exports the App component as the default export, making it available for import in other files.

Summary

This App component fetches photos from an API endpoint and manages the loading state. When the data is successfully fetched, it updates the state and renders the CardWrapper containing Card components for each photo. If no photos are found, it displays "Not found!". While loading, it displays "Loading . . .".


card.jsx

Image description

This code defines a functional component called card in JavaScript using JSX syntax, which is commonly used with React. This component takes a props object as an argument, and it is destructuring the state property from the props object to extract thumbnailUrl and title.

Here's a detailed breakdown:

1. Component Definition:
const card = ({state: {thumbnailUrl, title}}) => {
Enter fullscreen mode Exit fullscreen mode

This line defines a functional component named card. The function's parameter is an object, which is destructured to directly extract thumbnailUrl and title from the nested state property.

2. Return Statement:
return (
Enter fullscreen mode Exit fullscreen mode

This component returns JSX, which describes the UI of the component.

3. Card Structure:
   <div className="card">
     <img src={thumbnailUrl} alt="img" />
     <div className="p-4">
       <h1>{title}</h1>
     </div>
   </div>
Enter fullscreen mode Exit fullscreen mode
  • Outer div with card class: This div acts as the container for the card component.
  • img Element: This image element uses thumbnailUrl for its src attribute and has a default alt text of "img". This displays the image from the URL provided.
  • Inner div with p-4 class: This div adds padding around the text content of the card.
  • h1 Element: This header element displays the title text.
4. Export Statement:
export default card;
Enter fullscreen mode Exit fullscreen mode

This line exports the card component as the default export of the module, making it available for import in other parts of the application.


Top comments (0)