Styling in React Native: Step By Steps

Learn React Native with ease

Sudhir Kumar
8 min readMar 26, 2019
Photo from Pexels

It can be hard to understand why exactly clients pay so much for design work. After all, as long as you have a functional app, it doesn’t matter that much what it looks like, right?

Unfortunately, this simply isn’t the case. Styling is one of the most important aspects of your online presence. This doesn’t necessarily mean you need to pay an exorbitant amount of money for top-tier designers, but rather that you need to find a style that works for your business.

When it comes to React Native, styling becomes a little trickier. This is because the dynamics of styling for React and React Native are totally opposite. It becomes more brutal if you are coming from a back end domain. In this article, we are going to cover the basics of app styling and design in a step-by-step manner. We’ll begin with the following:

  1. StyleSheet in React Native
  2. FlexBox in React Native
  3. Handling images in React Native
  4. Custom fonts in React Native
  5. Positioning container and elements in React Native

StyleSheet in React Native

A StyleSheet is an abstraction similar to CSS StyleSheets. There are many ways to create styles for your component. Some developers prefer adding it to the bottom of each file, while others use a separate file and keep all the component’s styles in one place. By moving styles away from the render function, you’re making the code easier to understand. Here is the code to use StyleSheet in React Native:

import { StyleSheet } from “react-native”;const styles = StyleSheet.create({
container: {
flex: 1,
},
title: {
fontSize: 24,
fontWeight: 'bold',
},
});

No matter which option you choose, the declaration of StyleSheet remains the same for both the approaches.

Inline Styling

Like CSS, we can also provide inline styling to React Native.

<Text style={{fontSize: 24,color: "#fff"}}>Random Text</Text>
//styling with class styles and inline styles
<Text style={[styles.title,{fontSize: 24,color: "#fff"}]}>
Random Text
</Text>

Naming

Naming the styles is a good way to add meaning to the low-level components in the render function. No units such as px, pt, or rem are used in React Native. The values are based on screen size.

//It is advised that the styles are named using camel case.flexWrap: "wrap",
fontWeight: "900",
width: 200 | "100%",
height: 300 | "100%",
// There is no unit in React Native. You can use either of these to adjust styling.paddingVertical: 30,
paddingHorizontal: 20,

Reusability

Now, reusability depends totally on experience, but the more predictable and forecasting your code is, the better the chances are of reusing the same style for different case scenarios in the app or a website. When you are dealing with reusable styling to minimize the code length, always opt for styling that’s not component-specific and global in nature. You can easily assign custom values dynamically. This adds the freedom to customize the component at the run time and reduces the stress of predictability. color, size, weight, margin, and padding. All of this should be provided at the run time and should be assigned variable values during styling.

Color codes

Colors in React Native is similar to the CSS styling. We can use both hexadecimal and functional notation:

//All of these will give you the color black.color: "#000"
color: "black"
color: "rgba(0,0,0,0)"
color: "rgb(0,0,0)"

Learn more about colors and color codes here.

In React Native, you can create color variables like this. That way, if you want to change the color in the future, you can do so by changing it in only one place.

export const colors = {
white: '#fff',
black: '#000',
brand: "#c6bc9d",
}
// importing in the styles file like thisimport {colors} from "./colors";
export const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.brand,
},

Components in React Native

  1. View: The most fundamental component for building a UI, View is a container that supports layout with FlexBox, style, some touch handling, and accessibility controls. View maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a UIView, <div>, android.view, and etc.
<View style={styles.container}>
<View style={styles.inline}>
<Text style={styles.date}>READ MORE</Text>
<Text style={styles.date}> Date is </Text>
</View>
<Text style={styles.text}>{data.item.title}</Text>
</View>
</View>
//There should always be a parent in React Native if there's more than one View in the render function.//Major Styling properties for View are as follow: borderWidth: 4,
borderWidthColor: "red",
borderRightWidth: 4,
borderLeftWidth: 4,
borderTopWidth: 4,
borderBottomWidth: 4,
paddingVertical: 3,
paddingHorizontal: 3
zIndex: 100
// Shadow color in View
shadowColor: "red"
shadowOffset: "{width:3,height: 3}"
shadowOpacity: 3,
shadowRadius: 4

2. Text: A React component for displaying text.

<Text style={styles.baseText}>
<Text style={styles.titleText} Random Text</Text>
<Text numberOfLines={5}>
{this.state.titleText}{'\n'}{'\n'}
</Text>
</Text>
//Some major Text properties are as follows: fontSize: 30,
textAlign: "center" | "justify" | "left" | "right",
color: "red",
fontStyle: "normal" | "italic,
textDecoration: "underline" | "none" | "line-through"
fontFamily: "Roboto",
letterSpacing: 5,
textDecorationColor: "#fff",

FlexBox in React Native

If you’ve used FlexBox in CSS, Flex is not going to be any trouble for you. If you don’t have experience with FlexBox in CSS, I advise going through this link. Some important properties are as follows:

Flex direction: Default property is a column, and like in an app, the view is basically scrolling on the Y-axis — i.e. vertical (top to bottom) and not horizontal (left to right). So if you want to scroll across horizontally, you can use flexDirection: “row.”

Justify content: You can basically use the main options, which are flex-start, flex-end, space-between, space-around, and center.

  1. justify-content: “center”= aligns every child in the center.
  2. justify-content: “flex-end” = aligns every child to the end.
  3. justify-content: “flex-start”= aligns every child to the end.
  4. justify-content: “space-around” =aligns every child with equal spacing with each other.
  5. justify-content: “space-between” =aligns every child with equal spacing from each other. But the first and last child would be at the corners — either top or bottom or left or right.

Justify Content works for both row and column view. You can opt for styling using flex to avoid unwanted calculations of padding and margin.

Align items: It determines the alignment of children along the secondary axis. If the primary axis is a row, then the secondary is a column and vice versa. Just like justify-content, we have a few options: flex-start, flex-end, center, and stretch.

Flex wrap: It will work like flex-wrap in CSS. For example, if we have so many numbers of boxes and we did not mention flexWrap: ‘wrap’ property to them, then all the boxes render in the parent. But we’ll only see the number of boxes fit on the screen, not all the boxes. The default value flexWrap is nowrap.

flexWrap: ‘wrap’ | ‘nowrap’

Handling Images in React Native

React Native provides a unified way of managing images and other media assets in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:

<Image source={require('./my-icon.png')} />

This freedom to use the images in the app in any .png or .jpg format is an asset that’s not provided in the native app languages. You can also use the image URL to get the image source.

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />

You can learn more about the images here. When it comes to styling the images based on design, it’s best not to give a custom width and height to the images as it may alter view in various devices. However, we have a property resizeMode that can be used to align the image in a view. The syntax is as follows:

resizeMode: 'contain'
resizeMode: 'cover'
resizeMode: 'center'
resizeMode: 'stretch'

When an image is inside a view of a particular width and height, you can use any of the above properties to align the image with the parent div.

contain: It uses the original width and height of the image and aligns it within the parent div.

cover: It basically fills the whole view with the image. It’s usually best not to use it as it might cut some parts from the image in order to adjust the whole view.

center: It aligns the image to the center of the parent view — i.e it makes the image very small using padding — and it assigns it to the center of the parent view.

stretch: As the name suggests, it stretches the image and aligns it within the parent view. It’s best not to use it as it alters image quality.

Image Background: A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component.

<ImageBackground 
source={...}
style={{width: '100%', height: '100%'}}
>
<Text>Inside</Text>
</ImageBackground>

Dynamic handling of images: In case there is a scenario in which you want to show two different images based on any condition. You can easily manage the code like this:

var icon = this.props.active ? require('./my-icon-active.png'):  require('./my-icon-inactive.png');

<Image source={icon} />;

If you are using API to handle the image URL, then:

renderItem=(movies)=>
<TouchableOpacity style={styles.list}
onPress={()=>this.openModal(movies.item)}>
<Image style={styles.img} source={{uri: movies.item.poster}} /></TouchableOpacity>

Custom Fonts in React Native

We can use custom fonts in React Native. You can add your custom fonts by following these steps:

  1. Add fonts folder to asset library:

2. Package.json: add rnpm to package.json, providing the path to the font files:

"rnpm": {    "assets": [ "./assets/fonts/"    ]},

3. React Native link command to link it to font files:

react-native link

4. Once the terminal shows that the fonts have been linked, you can use it like this in the styling:

title: {
fontFamily: "Roboto",
fontSize: 30,
textAlign: "center",
},

Positioning Container and Elements in React Native

Position in React Native is similar to regular CSS, but everything is set to relative by default, so absolute positioning is always just relative to the parent. If you want to position a child using specific numbers of logical pixels relative to its parent, set the child to have an absolute position.

If you want to position a child relative to something that is not its parent, just don't use styles for that. Use the component tree. Check out this GitHub for more details on how position differs between React Native and CSS.

const styles = StyleSheet.create({container:{
backgroundColor: colors.red,
flex: 1,
position: "relative",
},
//relative parent for whole screen
close:{
position: "fixed",
top: 50,
right: 20,
zIndex: 100
},
//positions the close icon at the top-right of the screenmenu:{
position: "absolute,
bottom: 0,
left: 0,
width: "100%"
},
//positions the menu at the bottom of the screen})

Conclusion

Styling and design are a very vast concept and cannot be covered in one article. There might be some scenarios when you are stuck with some design or component and are unable to style it as needed. Let me know if there is anything missing or that needs an amendment. Together we will make this world a better and beautiful place.

--

--

Sudhir Kumar
Sudhir Kumar

Written by Sudhir Kumar

Email me for frontend and design work. I have delivered lots of projects. Website: https://codeindica.netlify.app/

Responses (2)