Home > OS >  How can I add the urls in `<img src="..."` to display images in different cards?
How can I add the urls in `<img src="..."` to display images in different cards?

Time:07-08

I'm using bootstrap cards in Next.js; I watched a tutorial about fetching API in Next.js and my code looks like this:

 export const getStaticProps=async ()=>{

  const res= await fetch('https://jsonplaceholder.typicode.com/photos');
  const data = await res.json();
  return {
    props:{test:data}
  }
 }








 function home({test}){
  return (
<div>      
  <ul className="nav nav-tabs">
    <li className="nav-item">
      <a className="nav-link " aria-current="page" href="#">
        Active
      </a>
    </li>

    
  </ul> 
  {test.map(tes=>(<div key={tes.id}><h1>{tes.url}</h1></div>))}
  <div className="card" style={{ width: "18rem" }}>
    <img src="..." className="card-img-top" alt="..." />
    <div className="card-body">
      
      <h5 className="card-title">Card title</h5>
      <p className="card-text">
        Some quick example text to build on the card title and make up the bulk of
        the card's content.
      </p>
      <a href="#" className="btn btn-primary">
        Go somewhere
      </a>
    </div>
  </div> 
</div>           
      
    )
 
 }
 export default home;

This code {test.map(tes=>(<div key={tes.id}><h1>{tes.url}</h1></div>))} displays the urls outside of the card; how can I add the urls in <img src="..." to display images in different cards?

image

CodePudding user response:

{test.map(tes=>(<div key={tes.id}>
  <div className="card" style={{ width: "18rem" }}>
    <img src={tes.url} className="card-img-top" alt="..." />
    <div className="card-body">
      
      <h5 className="card-title">Card title</h5>
      <p className="card-text">
        Some quick example text to build on the card title and make up the bulk of
        the card's content.
      </p>
      <a href="#" className="btn btn-primary">
        Go somewhere
      </a>
    </div>
    </div> 
</div>))}

You need to understand how map works The issue with your code is you are returning h1 but instead you need to return complete card div i suggest you to create a card component then pass props

CodePudding user response:

You displayed the url list in 'div' elems using the map method.

Do the same using an img tag instead of a div :

{test.map(tes =>
    (<img src={tes.url} className="card-img-top" alt="..." />)
)}

Cheers

  • Related