Using styled-components to achieve dynamic layouts in React Native

Clean up your styles by handling screen dimension variations in a styled-component

Jason Gaare
CompanyDev
3 min readJul 14, 2017

--

In our initial designs for our React Native application, all of our layouts were phone-focused. Then, once we took the initiative to optimize our layouts for tablets too, we discovered that we were writing a lot of conditional styles. Defining a shared constant proved helpful (here’s how we defined a tablet). Still, most of our stylesheets became bogged down with lines like this:

Further, we found ourselves repeating a lot of styles. If only there were a way we could create a component that could dynamically style itself…

Image source

Enter styled-components 💅

If you haven’t yet heard of styled-components, you should definitely check it out. I’d recommend watching this talk from React London 2017. Styled-components are the perfect way to clean up render functions within your components: extracting the styles and leaving you with your own custom component. It looks clean, and allows for rapid style replication across your app.

We are utilizing styled-components to unify the appearance of all the nested views within our settings page and also to simultaneously handle the layout for both phones and tablets. Here’s where what our settings page looked like on an iPad, using the styles we originally had in our application.

Functional, but slightly uncomfortable

Having the menu options stretch the full width of the screen feels right on a phone, but seems a little excessive on a tablet. We want to correct that, with only minimal changes to our code.

Each of our nested settings views have the same look and feel as this initial page, so using a styled-component already made sense. But now, we can also throw in our tablet conditional statements (used in a single place!) to dynamically layout on a phone or tablet.

Here’s a look at our styled-components (featuring a subtle padding change for tablets on line 5).

Note: You might also notice this is written as CSS rather than React Native styles. styled-components allows you to write either/or — just do what’s most comfortable for you!

The Results ✅

Using our new styled-components, here’s our new and improved settings layout on our iPad:

Padding for the win!

Ta-da! I’m no designer, but a little breathing room sure feels better to me.

Image source

Plus, look at how clean our render function is now:

Next steps 👉

This was our first exploration into utilizing styled-components in our React Native application. The library made it quick to replicate but not duplicate styles, plus it was a breeze to handle dynamic layouts. Moving forward, we’re definitely hoping to unify more of our views and move them into styled-components.

--

--

Jason Gaare
CompanyDev

Mobile developer at @CompanyCam. Husband, father, follower of Christ.