How to display data conditionally based on API response in React?

To display data conditionally based on an API response in React, you can follow these steps:

  1. Make a API call using a library like Axios or fetch in a useEffect hook or a function.
import React, { useEffect, useState } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState(null); useEffect(() => { axios.get('https://api.example.com/data') .then(response => { setData(response.data); }) .catch(error => { console.error(error); }); }, []); return ( <div> {data && data.length > 0 ? ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ) : ( <p>No data available</p> )} </div> ); } export default App;
  1. In the example above, we first fetch data from an API and store it in the data state using useState. We then conditionally render the data based on whether data is not null and has a length greater than 0.

  2. If the data is available, we map over it and render each item as a list item. If there is no data, we display a message saying "No data available".

  3. You can customize the conditional rendering logic based on your API response structure and requirements.