Search code examples
reactjsreact-hookscreate-react-app

Display array list from api in React JS


I am new to React and I am trying to display an array list from this api in an ordered list. This is the link where I am getting it from Chuck Norris.

[
  "animal",
  "career",
  "celebrity",
  "dev",
  "explicit",
  "fashion",
  "food",
  "history",
  "money",
  "movie",
  "music",
  "political",
  "religion",
  "science",
  "sport",
  "travel"
]

Here is my sample Code

import React from 'react';
import PropTypes from 'prop-types';

GetList.propTypes = {
    categoriesList: PropTypes.array,
};
GetList.defaultProps = {
    categoriesList:[],
}

function GetList(props) {
    const {categoriesList} = props;
    return (
        <ul className="post-list">
            {categoriesList.map(post=>(
                <li></li>
            ))}
        </ul>
    );
}

export default GetList;

Here is the App.js code where I make the api call

function App() {
  const [categoriesList, setCategoriesList] = useState([]);
  useEffect(() => {
    async function fetchCategoriesList(){
      try{
        const requestUrl = 'https://api.chucknorris.io/jokes/categories';
        const response = await fetch(requestUrl);
        const responseJSON = await response.json();
        console.log(responseJSON);
        setCategoriesList(responseJSON);
      } catch {

      }
    }

    fetchCategoriesList();
  }, [])
  return (
    <div className="App">
      <GetList />
    </div>
  );
}

It fetches the data and I can see it from console.log however it is not displaying. How can I go about displaying the list?.


Solution

  • You will need to pass a prop (categoriesList) to your GetList component:

    <div className="App">
      <GetList categoriesList={categoriesList} />
    </div>;
    

    And also in your component, you will need to render something from the array:

    <ul className="post-list">
      {categoriesList.map(post => (
        <li>{post}</li>  // <-- Here, need to put individual post
      ))}
    </ul>;