šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

CSS Grid to List view toggle

Let's see how to create a toggle button to display items in a grid or a simple one-column list. We will use just simple vanilla JavaScript and CSS Grid.

We will build the below example:

component example that changes its layout from CSS Grid to List

Using buttons we will toggle between the following:

  • a single-column list
  • a 2-column CSS Grid layout
  • a 3-column layout
  • a multi-column list where we will try to fit as many items as possible.

You can get creative and add or remove as many options as you need for the number of columns.

This is the starting markup for the grid:

<div id="main" class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

Toggling between grid view and list view is really only a matter of styling. What we need to do is to add a bit of JavaScript to add or remove classes:

const removeGridClasses = (container)=> {
    container.classList.remove(
        'grid-2-col', 
        'grid-3-col', 
        'grid-n-col'
    )
}
const setGridColumns = (num)=> {
    const container = document.getElementById("main")
    removeGridClasses(container)
    if (num !== 0) container.classList.add(`grid-${num}-col`)
}

The setGridColumns() will be called by each button with different parameters:

<button onclick="setGridColumns(0)">ā˜° List</button>
<button onclick="setGridColumns(2)">ā˜· Grid 2 columns</button>
<button onclick="setGridColumns(3)">ā˜· Grid 3 columns</button>
<button onclick="setGridColumns('n')">ā–¦ Multi columns</button>

And the final pice of the puzzle is the CSS classes:

.container { 
    &.grid-2-col {
        display: grid;
        grid-template-columns: 1fr 1fr;
    }

    &.grid-3-col {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
    }

    &.grid-n-col {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));

    }
}

You can see the full code here and you can play with the live example on GitHub pages.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *