NextJS: How to set background image dynamically

created at 02-01-2022 views: 163

What we need?

In my blog index page, I want to show the featured image for every item and, if any blog doesn't have a uploaded image, then the default image should be used.

The json data looks like:

{
    {
        "id": 7,
        "title": "test image ipload",
        "description": "dddd\r\n\r\nxxx",
        "featured_image": "http://127.0.0.1:8000/media/featured_image/3637164_-_Copy.jpg"
    },
    {
        "id": 6,
        "title": "post example",
        "description": "this is the content",
        "featured_image": null
    },
    ...
}

some have image, some not.

solution

So this would happen in the map() function:

function Blog({blogs})
    return (
        <div>
            {blogs.map(blog) => {
              var imageUrl = '/default-image.png';
              if(blog.featured_image !== null){
                  imageUrl = `${blog.featured_image}`;
              }
              return(
                <>  
                     <div
                         style = {{
                            backgroundImage:url(${imageUrl})
                         }}
                     >
                     </div>
                     // other information of this blog
                 </>
              )
            }
          }
        </div>
    )
export default Blog
  • /default-image.png: a default image in the public/ directory (if you created your app with create-next-app)
created at:02-01-2022
edited at: 02-01-2022: