Tips for incorporating inline images with gatsby-image

Seeking Solution

In my quest to query and showcase images with a maximum width of 350px, I am hoping to have them displayed inline-block for tablets and larger screens. Ideally, each image would sit next to one another and wrap if they exceed the parent div's size.


Problem Encounter

While I've successfully applied custom CSS styles, the images are not appearing inline or sometimes not rendered at all.


Current Outcome

I've experimented with various options like display: inline-block, float: left, overflow-wrap: break-word, and flex-wrap: wrap, but the images persist in displaying as block elements or remain invisible.


This is the code snippet:

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

import AccessoryStyles from "./accessory.module.css"

const Accessory = () => (
<StaticQuery
    query={graphql`
      query {
        allFile(
          filter: {
            extension: { regex: "/(jpg)|(jpeg)|(png)/" }
            relativeDirectory: { eq: "Lanka-Belt" }
          }
        ) {
          edges {
            node {
              childImageSharp {
                sizes(maxWidth: 350) {
                  ...GatsbyImageSharpSizes_withWebp
                  presentationWidth
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      const images = data.allFile.edges.map((image, index) => (
        <div className={AccessoryStyles.imageContainer}>
          <Img
            key={index}
            style={{
              maxWidth: image.node.childImageSharp.sizes.presentationWidth,
            }}
            sizes={image.node.childImageSharp.sizes}
          />
        </div>
      ))
      return {images}
     }
    }
 />
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Below are the custom styles defined in accessory.module.css:

.image-container {
  display: inline-block;  
}

https://i.sstatic.net/YCIhA.png

Despite spending two days scouring help forums like StackOverflow and GitHub issues related to Gatsby and Gatsby Image, I'm yet to find a resolution.

Your assistance would be highly appreciated. Thank you!

Answer №1

After discovering why the images were not rendering, I identified that images with a display property of inline-block would not render if the width CSS property was unspecified.

To address this issue, I directly set the width and display styles on the <Img /> component after passing data to it. As a result, the render function now appears as follows:

render={data => {
  const images = data.allFile.edges.map((image, index) => (
    <div className={AccessoryStyles.imageContainer}>
      <Img
        key={index}
        style={{
          maxWidth: image.node.childImageSharp.sizes.presentationWidth,
          width: image.node.childImageSharp.sizes.presentationWidth,
          display: "inline-block",
        }}
        sizes={image.node.childImageSharp.sizes}
      />
    </div>
  ))
  return {images}
 }
}
  • If you'd like these images to appear more visually appealing, consider applying display: flex and flex-wrap: wrap to the parent element of these images ;)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem with displaying error messages in an empty text field

I am facing an issue with displaying error messages when a text field is left blank. I would like a simple message, such as "can't be empty", to appear below the text field in red color when the user clicks the submit button and leaves multiple fields ...

Develop adaptable flex items

I am working with a container element that contains variable child elements whose width I want to scale. To see an example of what I'm trying to achieve, take a look at this simple plunker: https://plnkr.co/edit/ef0AGPsK7FJJyBqgWuMi?p=preview When ...

Display only specific PHP-encoded JSON data in a formatted table

After receiving a variable from PHP, I convert it to JSON as shown below: var myData = <?php echo json_encode($json_array) ?>; When I log the output, it looks something like this: 0: Carat: "0.70" Clarity: "VVS2" Color: "D" Cut: "Very Good" Polish ...

Encountering a peculiar issue with including no-cors in the header while fetching JSON content in a React.js application

As someone who is relatively new to react and nodeJS, I am currently experimenting with pulling JSON data from my nodeJS webservices and displaying it in a react component. let url = "http://codepen.io/jobs.json"; let iterator = fetch(url); iterator ...

express-locale: locales property not functioning as intended

I've been experimenting with using express-locale (v1.0.5) as middleware in my express app to identify the locale based on the browser request. My goal is to compare the identified locale with a list of 'allowed' locales and use a default i ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

How can I show a tooltip when hovering over a tab using uib-tab?

Currently facing an issue with HTML/Bootstrap. My tabs are displayed using the uib-tabset directive on Angular Bootstrap (UI Bootstrap). I am trying to implement a tooltip that appears when hovering over a tab that is disabled. Does anyone know how I can a ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

Did I accidentally overlook a tag for this stylish stripe mesh Gradient design?

I've been attempting to replicate the striped animated Gradient mesh using whatamesh.vercel.app. I've set up the JS file, inserted all the gist code into it, and placed everything in the correct locations, but unfortunately, it's not functio ...

table: column with percentage-based width AND a minimum width in pixels

Here is an example I'm working with: https://stackblitz.com/edit/js-ivvupc?file=index.html I need my table to be responsive, meaning it should become scrollable when the window size is reduced. The basic setup for this is already in place within the ...

Glowing effects on svg shapes

I'm looking to add a pulsing light animation around an SVG half circle shape that I have created. After experimenting with CSS and Webkit, the closest I've come is achieving a pulsing light around the parent element, rather than the actual shape ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

How is it possible that I am receiving two different outputs, with one of them even being undefined

I created a button using Jquery to submit POST data. It sends the value "name" : "kevin" in JSON format. $(document).ready(function() { $('#clickMe').on('click', function() { var data = {}; data.name="kevin"; ...

Tips for transferring the checkbox value in a React component

Good Day! I am facing a challenge passing a Boolean value of the checkbox using onChange since it is already being used to toggle the checkbox value. I am unsure of an alternative way to achieve this. Any guidance provided would be greatly appreciated. T ...

PHP script integration with WHMCS

I've been attempting to add analytic.php into head.tpl in WHMCS, but I keep encountering an error. Analytic.php location: root/analytic.php Head.tpl location: root/whmcs/template/six/includes/head.tpl I read that WHMCS supports Smarty PHP, so I&apos ...

The autofill ajax script is unable to populate dynamically added rows

As a newcomer to programming, I am trying to create a table that allows users to add new rows by clicking a button. Each row should have a field for inputting an ID which corresponds to some predefined numbers in another table, and then the other field sho ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Using Multiple SCSS Files to Reference a Centralized Style Sheet

I am currently developing a React application and facing an issue with my SCSS files. I have three SCSS files, one main file that contains theme variable colors, and the other two are located in component folders. When I import the main SCSS file into the ...

Zurb Foundation - Building a personalized form, but encountering issues with post creation functionality

After integrating Foundation Forms into my website to create a form, I am facing an issue where the post is not being created. Below is the HTML code snippet: <div style="padding-bottom: 5px; padding-top: 10px;"> <label> <h3><sma ...