Now that I’m through my third week of learning React Native, I wanted to cover my favorite part — styling. If you’re familiar with styling (coding how your app looks) on the web, be it through core React, vanilla JavaScript, or your choice language/framework, you know that you implement a CSS (Cascading Style Sheets) file that references certain HTML elements and manipulates certain style properties. With React Native, this isn’t case — components are styled through JavaScript objects that you conventionally code directly beneath your component by creating a constant style
that you pass as a prop to each of React Native’s core components like <Text />
or <View />
. While inline styling is acceptable, as components get more and more complex it becomes necessary (and honestly just best practice) to create a const
called styles
and set it equal to StyleSheet.create
which builds an object of objects that contain style properties referenced in camel casing, i.e. backgroundColor
. It may seem strange at first if you are used to CSS but most every style property that I’ve come across is similar if not the same.
The image above is a sample output from a very basic example to explain StyleSheet further. { StyleSheet }
was imported from 'react-native'
and was implemented from the const styles = StyleSheet.create{()};
. Within the parentheses of the create function we give key-value pairs where the key is the name you wish to give the particular element, i.e. container
or bigHeader
. As you can see below I created a View
with three Text
components. These are core components we import from React Native as seen below — consider them like streamlined constraints for your code as opposed to core React which uses JSX.
Now if we scroll down under the App
component, you will see I have created a const
object called styles
which I will set the style
prop equal to. There we will use the camel cased style properties, very similar to CSS.
While it may seem daunting at first in that you have to learn a whole new set of properties to make your app not look awful, this convention lends itself you helping you out in VSCode not only with autofill, but also by using ctrl
+ C
to see the list of options. There’s also an amazing cheat sheet for reference.
Now get out there and create some great looking mobile apps with React Native’s { StyleSheet }
core component!
Sources