Logo

dev-resources.site

for different kinds of informations.

Moving a Square with CSS Grid and Minimal JavaScript

Published at
10/7/2023
Categories
react
css
grid
javascript
Author
jcvb
Categories
4 categories in total
react
open
css
open
grid
open
javascript
open
Author
4 person written this
jcvb
open
Moving a Square with CSS Grid and Minimal JavaScript

In a recent technical interview, I was tasked with a problem where a square had to be moved within a grid using buttons. The solution I initially thought of required more complex logic and JavaScript, but I realized I could use CSS Grid to handle most of the heavy lifting. In this post, I'll explain how I used grid properties to solve the problem with minimal JavaScript.

Example

example

The Problem

I had to move a square within a grid with the help of four buttons: up, down, left, and right. The grid and buttons are defined as follows:

.grid {
  display: grid;
  grid-template-columns: repeat(11, 20px);
  grid-template-rows: repeat(17, 20px);
}

.square {
  grid-column-start: 6;
  grid-row-start: 9;
  background-color: red;
}

.btn {
  display: grid;
  width: 100%;
  height: 100%;
}

.btn-up {
  grid-column-start: 2;
  grid-column-end: 11;
}

.btn-down {
  grid-column-start: 2;
  grid-column-end: 11;
  grid-row-start: 17;
}

.btn-right {
  grid-column-start: 11;
  grid-row-end: 17;
  grid-row-start: 2;
}

.btn-left {
  grid-column-start: 1;
  grid-row-end: 17;
  grid-row-start: 2;
}
Enter fullscreen mode Exit fullscreen mode

The JavaScript Solution with React

Instead of manually moving the square's position in the DOM, I used CSS grid properties combined with React's state to determine the square's position on the grid.

Here's the JavaScript code:

import React, { useState } from "react";

const Board = () => {
  const [axisX, setAxisX] = useState(6);
  const [axisY, setAxisY] = useState(9);

  const handleMoveSquare = (direction) => {
    switch (direction) {
      case "up":
        if (axisY > 2) setAxisY(prevY => prevY - 1);
        break;
      case "down":
        if (axisY < 16) setAxisY(prevY => prevY + 1);
        break;
      case "right":
        if (axisX < 10) setAxisX(prevX => prevX + 1);
        break;
      default:
        if (axisX > 2) setAxisX(prevX => prevX - 1);
        break;
    }
  };

  return (
    <div className="grid">
      <div className="btn btn-up">
        <button onClick={() => handleMoveSquare("up")} />
      </div>
      {/* ...other buttons... */}
      <div className="square" style={{ gridColumnStart: axisX, gridRowStart: axisY }}></div>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Demo

Conclusion

CSS Grid properties combined with React's state management provide a powerful way to create dynamic interfaces without much manipulation of the DOM. By setting the grid properties dynamically based on React's state, we can create fluid interfaces that react to user interactions.

Would love to hear your thoughts on other creative uses of CSS Grid!

grid Article's
30 articles in total
Favicon
GridLookout: Building Viewport-Aware Multi-Layer Grid Positioning Of React Components
Favicon
Easily Integrate Syncfusion UI Components into PowerApps
Favicon
Mastering Flutter DataGrid with Pagination: Build Efficient Data Tables
Favicon
Flexbox vs Grid: A Guide to Choosing the Best Layout with Examples
Favicon
Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List
Favicon
Learn CSS Grid: Simple Guide with Plenty of Examples
Favicon
Grid Layout: The Ultimate Guide for Beginners
Favicon
Unlocking the Power of CSS Grid for Modern Web Design
Favicon
Make a grid element span to the full width of the parent
Favicon
Balance strategy and grid strategy
Favicon
From Requirements to Code: Implementing the Angular E-commerce Product Listing Page
Favicon
Bootstrap Tutorials: Grid system
Favicon
🎲 Criando um Dado com Flexbox e CSS Grid Layout
Favicon
Simple grid strategy in Python version
Favicon
How To Set Up Docker Selenium GRID
Favicon
React feature rich Table/Grid Libraries every developer should know.
Favicon
Adding Gif Canvas Features : Grid Snap
Favicon
Flex vs. Grid: Choosing the Right CSS Layout
Favicon
How to Create Instagram Explore Grid Layout with React Native
Favicon
#Fashion #Hero #Container #Using #Grid and #Flex
Favicon
Grid de 8 pontos uma técnica que torna seu projeto escalável
Favicon
Quick guide to CSS Grid
Favicon
VueJS + CSS: grid template based on variable
Favicon
Learn Css Grid Style Layout In 10 Minutes
Favicon
Get in to the Grid: Style Elements Made Easy
Favicon
React Grid Collection
Favicon
How To Center An Elements With CSS Grid
Favicon
Moving a Square with CSS Grid and Minimal JavaScript
Favicon
Introducing the AG Grid Figma Design System
Favicon
AWS Grid computing for Capital Markets (FSI)

Featured ones: