Exploring the power of CSS grid in React/Gatsby for creating dynamic layouts with varying numbers of columns in each

I need help creating a dynamic grid layout where the number of columns alternates between rows. For example, I want the first row to have one column, the second row to have two columns, and so on. Right now, my grid only has two columns per row. Does anyone know how I can achieve this? Thank you!

Current code snippet:

<div className="grid grid-cols-2 gap-10">
  {projects.map(({ node }, index) => {
    const title = node.frontmatter.title || node.fields.slug
    const client = node.frontmatter.client
    const category = node.frontmatter.category
    const image = node.frontmatter.image.childImageSharp.fluid
    const description = node.frontmatter.description

    return (
      <div className="col-span-1">
        <Link to={node.fields.slug}>
          <BgImg fluid={image} className="h-104 bg-cover bg-no-repeat flex flex-col justify-end hover:shadow-2xl transition-all ease-linear duration-300" key={node.id}>
          </BgImg>
        </Link>
        <div className="py-5">
          <h3 className="text-2xl font-regular"><span className="font-semibold">{client}</span><span className="mx-1">—</span>{title}</h3>
          <p className="text-xl mb-4 font-light">{description}</p>
        </div>
      </div>
    )
  })}
</div>

Answer №1

If you want the 1-column rows to stretch across the entire width like this:

[content] [content]
[      content    ]
[content] [content]

Instead of like this:

[content] [content]
[content]
[content] [content]

You can easily achieve this in TailwindCSS by doing the following:

<div className="grid grid-cols-2 gap-10">
  {projects.map(({ node }, index) => {
    const title = node.frontmatter.title || node.fields.slug
    const client = node.frontmatter.client
    const category = node.frontmatter.category
    const image = node.frontmatter.image.childImageSharp.fluid
    const description = node.frontmatter.description

    return (
      <div className={index % 3 == 2 ? "col-span-2" : "col-span-1"}>
        <Link to={node.fields.slug}>
          <BgImg fluid={image} className="h-104 bg-cover bg-no-repeat flex flex-col justify-end hover:shadow-2xl transition-all ease-linear duration-300" key={node.id}>
          </BgImg>
        </Link>
        <div className="py-5">
          <h3 className="text-2xl font-regular"><span className="font-semibold">{client}</span><span className="mx-1">&mdash;</span>{title}</h3>
          <p className="text-xl mb-4 font-light">{description}</p>
        </div>
      </div>
    )
  })}
</div>

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

Error occurred during React npm module build due to failure in ./node_modules/babel-loader/lib/index.js

While setting up my React environment, I encountered two errors when running npm start in the command prompt. The first error states "module build failed (from ./node_modules/babel-loader/lib/index.js)" and the second error is "error plugin/preset files a ...

The Axios post request is mistakenly sending my data as the key with an empty value instead of sending the entire data object itself

I began by developing the frontend, but now I am looking to create the backend in order to establish a connection with a database. const express = require("express"); const bodyParser = require("body-parser"); const cors = require(" ...

Applying a distinct CSS style to the final entry of each list item

Is there a way for me to assign a different style for the last entries in my code? <?= $k % 2 == 1 ? 'news-figure' : 'news-figure-b' ?> ...

redux-toolkit extraReducers not triggering

I've been experimenting with createAsyncThunk, but I'm having trouble getting the extraReducers to trigger. This is what my current setup looks like: export const getAllAgents = createAsyncThunk( "getAllAgents", async (token: string ...

Tips for adding a CSS class to an HTML element on-the-fly

As a newcomer to JavaScript and AngularJS, my question may be considered naive by some. I am currently working on a tutorial project involving AngularJS. Here is the HTML code snippet I am dealing with: <link href="http://netdna.bootstrapcdn.com/boo ...

Vue's smooth scrolling in Nuxt.js was not defined due to an error with the Window

There seems to be an issue with adding vue smooth scroll to my nuxt.js project as I'm encountering the "window is not defined error". The steps I followed were: yarn add vue2-smooth-scroll Within the vue file, I included: import Vue from 'vue ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Ensure that the URL is updated correctly as the client navigates between pages within a Single Page Application

Seeking a solution for maintaining the URL in a Single Page application as the client navigates between pages, with the URL changing in the background. I attempted using @routeProvider but it doesn't seem to be suitable for my situation. Any suggestio ...

Encountered an error when attempting to load the external module @babel/register during the

My React project runs smoothly on my VMware, but when I cloned the same app and executed the gulp command, I encountered an error during compilation: MacBook-Pro:Frontend1.0 apurvgandhwani$ gulp [18:42:31] Failed to load external module @babel/register ...

Having a floating left <UL> list with floating right text boxes positioned below the UL list instead of being set next to it

I'm attempting to align an unordered list on the left and a group of textboxes on the right within a div tag. The problem I'm facing is that the text boxes are positioned below the list items instead of being adjacent to them. .PersonLI { flo ...

Prevent the default scroll event triggered by the mousewheel in certain situations. It is not possible to use preventDefault within a passive event

I have a div element with the onWheel attribute. By default, the browser interprets onWheel as scroll behavior. However, I want to prevent the browser's default mouse behavior under certain conditions. Unfortunately, I encountered an error that say ...

Even after reaching the bottom of the page, the div for overlay projects continues to scroll

*{ margin: 0; padding: 0; } body{ font-family: helvetica , sans-serif; background-color: #1E1E20; } .parallax-container { /* The image used */ background-image: url("https://i.sstatic.net/BlF.jpg"); animation-name: pixels; animation-durat ...

Dynamic content in NextJS: First, statically render a page and then customize it with user-specific data

I need advice on how to handle a specific data fetching scenario with NextJS static page rendering. We have a page that showcases articles, similar to this example. The content is the same for all users (perfect for static rendering), but lock icons should ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

Receiving constant errors on Search Input in React: continuously encountering the error "Cannot read property 'value' of undefined."

Attempting to incorporate the < ChipInput /> element from https://github.com/TeamWertarbyte/material-ui-chip-input. Using material-UI react component, my current setup includes: A functional search input bar. When an artist's name is typed, it ...

Columns in Bootstrap4 housing elements positioned absolutely

Recently, I've been developing a game that involves using absolute positioning for certain elements. This is necessary for creating moving animations where elements need to slide around and overlap to achieve a specific effect. As I focus on optimizi ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Implementing dynamic content loading using CSS and jQuery upon link/button activation

I'm facing an issue where I am attempting to align content to the left side of my screen to display a feed while also ensuring that the pushed content is responsive. Unfortunately, the feed is not visible and the content remains unresponsive. Is ther ...

How can I prevent a CSS class from being rendered in a specific view within MVC?

My knowledge of CSS is quite limited and I am fairly new to it. In my MVC application, I am using a theme that relies on Bootstrap. In the _layout view of my application, I have the following code: <div class="container body-content"> @Html.Par ...

Tips for effective state management when using both React router and Redux

I am currently working on retrieving data from an API which is stored in a variable called items. { '001': {id: '001', name:'foo',color:'blue' }}, '002': { id: '002',name:'bar',color:&a ...