Display List of Items From Api in React

In this post i will show you how to display list of items from api in react

first of all create a component to display single component from list. This component will simply show the rows of table based on data from api

export const ItemComponent ({data}) => {
    return (
         <tr>
                <td>{data.id}</td>
                <td>{data.title}</td>
                <td>{data.body}</td>                      
         </tr>
    )
}

As you can see the above component will print the rows of table based on data passed to that component

now lets create a main component which will fetch data and show the data in table format from api

below is our main component

import React, { useState, useEffect } from 'react'
import Axios from 'axios'

export const MainComponent () => {

    const [data, setData] = useState([])
    useEffect(()=>{
        Axios.get("https://jsonplaceholder.typicode.com/posts").then(d => {
            if(d.status == 200){
                setData(d.data)
            }
        })
    },[])
    
    return (
        <table>
            {
                data.map(list=>{
                    return <ItemComponent data={list}/>
                })
            }
        </table>
    )
}

comments powered by Disqus