Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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> ))
about 4 years ago · Juan Pablo Isaza Report

0

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> ))
about 4 years ago · Juan Pablo Isaza Report

0

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> ))
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!