Home > Software engineering >  How get fetch api data with categories in react js?
How get fetch api data with categories in react js?

Time:08-16

[![enter image description here][1]][1]So I have such a task. When the buttons are clicked, information corresponding to the api category should appear. And all button must be default For example, when you press the science button, the information (author, date, title etc) of the science category should appear. How can I do this? Most likely categories should be passed with props. But I don't know how to do it.

Api link is : this https://github.com/vamgan/Inshorts-News-API

import React, { useEffect, useState } from 'react'
const App = () => {

  const [state, setState] = useState([])

  useEffect(() => {
    fetch('https://inshorts-api.herokuapp.com/news?category={sports}')
      .then(res => res.json())
      .then(res => setState(res.data))
  }, [])
  return (
    <>
      <div className='d-flex'>
        <button>All</button>
        <button>Business</button>
        <button>Sports</button>
        <button>World</button>
        <button>Technology</button>
        <button>Entertainment</button>
        <button>Science</button>
      </div>

    </>
    // {
    //   state.map((item)=>(
    //     <img src={item.imageUrl} alt="" />
    //   ))
    // }
  )
}

export default App

CodePudding user response:

import React, {  useState } from "react";
const App = () => {
  const [state, setState] = useState([]);
  const Category = [
    "All",
    "Business",
    "Sports",
    "World",
    "Technology",
    "Entertainment",
    "Science",
  ];
  const fetchValue = (category) => {
    fetch(`https://inshorts-api.herokuapp.com/news?category=${category}`)
      .then((res) => res.json())
      .then((res) => setState(res.data));
  };
  const CategoryButton = ({ category }) => (
    <button onClick={() => fetchValue(category)}> {category}</button>
  );
  return (
    <>
      <div className="d-flex">
        {Category.map((value, index) => {
          return <CategoryButton category={value} key={index} />;
        })}
      </div>
      <br />
      {state?.map((data) => {
        return (
          <div >
            <img src={data.imageUrl} alt="Avatar" style={{ width: "300px" }} />
            <div >
              <h4>
                <b>{data.author}</b>
              </h4>
              <p>{data.content}</p>
            </div>
          </div>
        );
      })}
    </>
  );
};
export default App;


  • Related