Save time and effort sourcing top tech talent

Getting to Grips with Styled-Components

Aug 27, 2019
hackajob Staff

Ever wondered about Styled-Components? If you’re a web developer, you’ll know that they allow you to write CSS code for components in React Native. In fact, they can help to ease your path through React Native entirely. Best known for helping to reuse certain code or components, styled-components can help save time when writing lots of different code.

Before starting this tutorial, we recommend reading some of our previous articles on React Native so you can see what we’ve worked on previously.

Without further ado, let’s begin.

First, start the project:

react-native init styledComponents && cd styledComponent

Don’t forget to install the library:

npm i --save styled-components

We’re now ready! We’ll have a single-page app with a button, text input and a view (with a different background colour and text) inside:

Using the default React Native components, our code will look like the following:

And the app will look like this:

It’s not a big deal to write the lines of code above, after all, we have some tags and styles and most importantly; the code itself is written. But sometimes, creating an app requires a little more effort and can feature multiple screens, lots of components and some complex CSS styles.

The best way to deal with this? Reuse components. After all, why would you want to re-write the button component again and again for every screen? Note that you don’t need styled components in order to do this, however, if you have some web dev knowledge, styled components will certainly make your path a little bit easier.

Writing styled components

Create a new file called 'styledComponents.js' and import the library:

Note that we have a “/native” on our import statement, because styled components works for both ReactJS and React Native.

The first component you’ll write is the ‘SafeAreaView’:

You’ll use ( ` ) and backticks to write your CSS code, starting right after the component you want to use.

Header:

Text:

Text Input:

Button:


Next, you need to substitute the old components for the new ones above. Simply import the components above to the ‘App.js’ file and delete the older imports.

Your code should now look like this:

Take a look at the final appearance of your app:  

Does it look familiar? 😉It should look exactly the same, which is entirely the point.

Within this tutorial, you were able to learn about the basics of styled-components. If you fancy continuing your learning, make sure to access the full documentation (for both basic and advanced styled-components). You can find the code used to create this tutorial here.

Like what you’ve read? As part of the hackajob platform, you get full access to an entire library of coding challenges for free. Make sure to sign up and see how well you score.