I am trying to get data using API and loop it for banner images.
I got the data. And it is working fine. Here is the code to get the data.
///Retrieving data using API
const [post, setPost] = useState(null);
useEffect(() => {
axios.get(global.url 'api/welcome').then(response => {
setPost(response.data);
});
}, []);
Now, I want to show images in the banner. In the first loop div class needs to <div className="carousel-item active">
as shown in the image. From the second loop active need to be removed to be like: <div className="carousel-item">
.
////Looping for banner images
post[1].data.map((banner_image) => (
<div>
<div className="carousel-item active">
<img src="image source here" className="d-block w-100" alt="" />
</div>
</div> ))
In this case how to use the if
condition? I am very new to React Js.
Thank you, in advance.
CodePudding user response:
You could do conditions in your JSX this way:
Notice the {} for className.
post[1].data.map((banner_image, index) => (
<div>
<div className={"carousel-item " index === 0 ? "active" : ""}>
<img src="image source here" className="d-block w-100" alt="" />
</div>
</div> ))
CodePudding user response:
Try this
////Looping for banner images
post[1].data.map((banner_image, idx) => (
<div key={idx}>
<div className={`carousel-item ${idx === 0 ? "active" : ""}`}>
<img src="image source here" className="d-block w-100" alt="" />
</div>
</div> ))
CodePudding user response:
You can use template literals in JSX.
post[1].data.map((banner_image, index) => (
<div key={`uui-${index}`}>
<div className={`carousel-item ${index === 0 ? 'active' : ''}`}>
<img src="image source here" className="d-block w-100" alt="" />
</div>
</div> ))