Make a Flexbox React Component

Components that scale with the size of the window in just 27 lines of code

Kris Guzman
Better Programming

--

Let’s make one ourselves

Flexbox is an invaluable tool. Many component libraries such as Material-UI and Semantic UI provide components that use Flexbox under the hood.

There are smaller libraries that attempt to wrap Flexbox into a component, but most are extremely outdated or the API just isn’t… Flexbox enough.

The Dark Ages of Wrapper Divs

Have you ever written a container div and realized it’s just a div with flex properties?

Have you ever made a whole styled component as a one-off with just flex properties, then struggled to name it? Maybe you called it FlexWrapper or FlexColumn.

Here’s an example of a div just being used for layout.

If you have worked on a large project, you know that this can get messy really quickly.

Ideally, we want something like this:

So, How Do We Build It?

We are going to make this dead simple. You will be able to copy and paste the code and modify it as much or as little as you want. The goal is to make it universally usable, and pure React.

Ready…?

No, seriously… this is going to be quick… are you paying attention?

Here it is!

It’s so simple… yet so useful

Sometimes, you really have to appreciate the simple things in life. Who knew a component like this would be one of them?

There are features missing like spreading props, swapping elements (example: swap div for a button or header tag), and other things you may find handy.

But because it’s so simple, it’s easy to modify from here. This should be enough for 80% of use cases.

What Did We Gain Here?

  • An API that corresponds to the Flex API. The only extra prop we have is container to decide whether or not to use display: flex, and maybe a few helpful properties like className, width, height, padding, and margin.
  • Less code. Instead of writing a bunch of separate, one-off styles for each of our divs, we just use the Flex component. Fewer styles to manage!
  • Faster prototyping. Sometimes, you just want to get a prototype up as fast as possible. The Flex component is all about saving time.
  • Easier to read. When you see a Flex component, you see the props and you know exactly what it does. You don’t have to worry about coming up with obscure names.
  • Library free and universally usable. We aren’t using anything but React, and there is nothing extra-bloating our codebase.

TypeScript and Flow

I haven’t forgotten about my Typescript and Flow users out there. Here are types for both, for your convenience.

Sandbox Example

Here is a link to a full Sandbox example so you can play around with it.

--

--

Front end developer. On a mission to explore the world & build amazing software. Connect with me on LinkedIn: https://www.linkedin.com/in/kristopher-guzman/