Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, how to use if condition inside a div to change its className?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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> ))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading