DEV Community

Cover image for Centering UI Components: A Fun Dive into React's Flexibility
Othman Adi
Othman Adi

Posted on

Centering UI Components: A Fun Dive into React's Flexibility

Introduction

Hello, fellow code enthusiasts! Ever found yourself staring at uneven boxes in your React app, itching to center them, but just couldn't find that perfect solution? 🧐 Today, I'm going to show you a simple yet effective tweak I made to enhance the aesthetics of a React component. Let's turn that itch into a satisfying scratch! 🚀

Image description


The Old Code: An Overview

Let's start by looking at the initial code:

// ...
<div className="row gy-5 mt-5">
  {services.length > 0 &&
    services.map((service, index) => (
      <div className="col-sm-6 col-lg-4 wow fadeInUp" key={index}>
        {/* ... rest of the service box */}
      </div>
    ))}
</div>
// ...
Enter fullscreen mode Exit fullscreen mode

In this snippet, our boxes are neatly aligned in rows. It works perfectly when there's an even number of boxes. However, when the number isn't even, the last row might look a bit... well, off-center.


The Basics

The goal here is to ensure that if the services are not in multiples of 3 (or any other grid you choose), the last row should center its boxes.

The magic lies in Flexbox. With the Bootstrap grid system (which I assume we're using given the class names), rows are inherently flex containers. So, if a row contains fewer columns than expected, you can make them center themselves using mx-auto.


Advanced Understanding

The new code introduces a neat condition to dynamically add the mx-auto class when needed:

<div
  className={`col-sm-6 col-lg-4 wow fadeInUp ${services.length - index <= 2 ? "mx-auto" : ""}`}
  key={index}>
  {/* ... rest of the service box */}
</div>
Enter fullscreen mode Exit fullscreen mode

The logic here is simple but powerful:

  • Subtract the current index from the total number of services.
  • If the result is 2 or less, it means we are on the last row (given a 3-column layout).
  • The mx-auto class is then added to center the columns.

Key Points

  1. Dynamic Class Names: React allows for dynamic class names using template literals. This makes UI responsiveness based on data super intuitive.
  2. Flexbox Magic: Bootstrap's grid system, powered by Flexbox, gives us handy utilities like mx-auto to auto-margins elements, a simple technique with dramatic effects.

Image description


Interesting Facts

  • Why Flexbox?: Introduced in CSS3, Flexbox is a layout model that allows items in a container to be dynamically arranged based on specific criteria, even when sizes are unknown or dynamic. In our case, it's about centering elements.

  • Why not CSS Grid?: While CSS Grid is powerful and offers two-dimensional layouts (rows and columns), Flexbox's linear layout was just what we needed for this tweak.


How to Go Further

Feel confident with this change? Awesome! Here are some ideas to elevate your game:

  1. Responsive Behavior: Depending on the viewport, decide how many boxes to show per row and adjust the centering logic accordingly.
  2. Transitions: Introduce subtle animations when the boxes rearrange themselves.
  3. Interactivity: Allow users to decide the layout and remember their preference.

What Else Can Be Changed?

The world (or code) is your oyster! Consider:

  • Theming: Introduce a dark mode or allow users to pick their color palette.
  • Content Loading: Display skeleton screens as placeholders till the content loads.
  • Engaging UI: Use micro-interactions to make your UI elements more engaging.

Wrapping Up

There you have it, a small tweak with a significant impact. React and Flexbox are a match made in heaven, and with a sprinkle of Bootstrap magic, you can achieve wonders!

Eager to learn more? I've got you covered. Follow me on Instagram @Codingwithadi for fun coding snippets and on GitHub at OthmanAdi for some serious code magic. 🪄

Till next time, keep those fingers coding and brains churning! 🚀👨‍💻👩‍💻

Oldest comments (0)