1

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.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • Also it might be prettier to define your URL as `\`${global.url}/api/welcome\`` instead of `global.url+'/api/welcome'`. – anteAdamovic May 24 '22 at 10:14
  • You will see that none of the answers actually use an if-statements. This is because if-else statements are not possible to use inside jsx. https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs See also the react.js docs: https://reactjs.org/docs/conditional-rendering.html – Håken Lid May 24 '22 at 10:21

3 Answers3

2

You could do conditions in your JSX as below. 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> ))
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
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> ))
Pranava Mohan
  • 533
  • 2
  • 8
  • 18
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> ))
Jay Patel
  • 218
  • 2
  • 8