Make a Flexbox React Component
Components that scale with the size of the window in just 27 lines of code
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
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.
No, seriously… this is going to be quick… are you paying attention?
Here it is!
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
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
containerto decide whether or not to use
display: flex, and maybe a few helpful properties like
- Less code. Instead of writing a bunch of separate, one-off styles for each of our divs, we just use the
Flexcomponent. Fewer styles to manage!
- Faster prototyping. Sometimes, you just want to get a prototype up as fast as possible. The
Flexcomponent is all about saving time.
- Easier to read. When you see a
Flexcomponent, 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.
Here is a link to a full Sandbox example so you can play around with it.