To display data conditionally based on an API response in React, you can follow these steps:
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;
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.
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".
You can customize the conditional rendering logic based on your API response structure and requirements.