Styling in React Native

Styling in React Native

Styling in React Native: Explore the best ways to style a React Native application

Explore the best ways to style a React Native application

If you are just started with React Native or even you are experienced with it, you may find the styling a little bit challenging for the first time. that happens when you come especially from the web background and when you try to write React Native style as you usually do when you write CSS on the web and you find out what you expected. the method that React Native use for styling use CSS properties and it’s actually not the same as normal CSS. anyway, we are going to see how we do styling in React Native, in addition, to React Native style method styling method, we will explore the different ways to style a React Native application.

React Native style method

React Native give us two powerful ways by default to style our application :

Style props

You can add styling to your component using style props you simply add style props to your element it accepts an object of properties.

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
export default class App extends Component<Props> {
render() {
return (
<View style={{flex:1,justifyContent:"center",backgroundColor:"#fff", alignItems:"center"}}>
<View style={{width:200,height:150,backgroundColor:"red",padding:10}}>
<Text style={{fontSize:20, color:"#666"}}>Styled with style props</Text>
</View>
</View>
);
}
}

If you look at our code, we use the CSS properties with the capital letter, notice that some properties are not supported in react-native, an error will throw when you try to use any unsupported property, CSS3 animations are not supported instead React Native leave that to the animation API

React Native use Flexbox for layout, it’s a great tool to define the layout of your React Native app, elsewhere it’s not working as the same as in CSS but genuinely it’s easy to use and flexible.

import React, {Component} from 'react';
import { Text, View} from 'react-native';
export default class App extends Component<Props> {
render() {
return (
<View style={{flex:1,justifyContent:"center",backgroundColor:"#fff", alignItems:"stretch"}}>
<View style={{flex:1,backgroundColor:"red"}}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={{flex:1,backgroundColor:"blue"}}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={{flex:1,backgroundColor:"purple"}}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={{flex:1,backgroundColor:"orange"}}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
</View>
);
}
}

React native flexbox is a great way to deal with the layout manipulation it so easy to design your layout but you need some basic understanding of flexbox to get your head it, you can check this great article for a better understanding.

Using StyleSheet

if you have a large code base or you want to set many properties to your elements, writing our styling rules directly inside style props will make our code more complex that’s why React Native give us another way that let us write a concise code using StyleSheet method:

First, make sure to import StyleSheet from react-native

import { StyleSheet} from 'react-native';

And try to assign some style properties using create method that takes an object of properties.

const styles = StyleSheet.create({
container: {
flex:1,
justifyContent:"center",
backgroundColor:"#fff",
alignItems:"stretch"
},
title: {
fontSize:20,
color:"#fff"
},
item1: {
backgroundColor:"orange",
flex:1
},
item2: {
backgroundColor:"purple",
flex:1
},
item3: {
backgroundColor:"yellow",
flex:1
},
item4: {
backgroundColor:"red",
flex:1
},
});

And then we pass the styles object to our component via the style props:

<View style={styles.container}>
<View style={styles.item1}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item2}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item3}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item4}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
</View>

Our code looks more concise with StyleSheet method and the result still the same:

The styling method that React Native use has really great features that allow as to do some dynamic styling but it’s limited especially when it comes to applying some CSS properties that aren’t supported by React Native, for example, applying box-shadow to your components you may have to do the following :

const Card=()=>(

 <View style={styles.card}>

  <Text>Hello!</Text>
</View>
)

//our style

 const styles=StyleSheer.create({

card:{
width:100,
height:120,
shadowColor: '#000000',
    shadowOffset: {
      width: 0,
      height: 3
    },
    shadowRadius: 5,
    shadowOpacity: 1.0} 
})

Whereas if we have to do the same and adding shadow in CSS:

.card{
width:100px,
height:120px,
box-shadow:0 0 5 #000000;
}

It’s easier to do it with CSS, we all would love to the same in React native, unfortunately, we can’t write CSS directly in React Native. but no worries the good news is styled-component support React Native 💣

styled-component in React Native

Yes, you can use styled-component with React native so you can write your styles in React Native as you write normal CSS. and it’s easy to include it in your project and it doesn’t need any linking just run this following command inside the root directory of your app to install it:

yarn add styled-components

And then simply start using it in your components:

import React, {Component} from 'react';
import { StyleSheet,Text, View} from 'react-native';
import styled from 'styled-components'
const Container=styled.View`
    flex:1;
    padding:50px 0;
    justify-content:center;
    background-color:#f4f4f4;
    align-items:center
`
const Title=styled.Text`
font-size:20px;
text-align:center;
 color:red;
`
const Item=styled.View`
flex:1;
border:1px solid #ccc;
margin:2px 0;
border-radius:10px;
box-shadow:0 0 10px #ccc;
background-color:#fff;
width:80%;
padding:10px;

`

export default class App extends Component {
  render() {
    return (
      <Container>
             <Item >
             <Title >Item number 1</Title>
             </Item>
             <Item >
             <Title >Item number 2</Title>
             </Item>
             <Item >
             <Title >Item number 3</Title>
             </Item>
             <Item >
             <Title >Item number  4</Title>
             </Item>
      </Container>
    );
  }
}

So cool 😃. now you can totally write CSS with React Native and we give that to [styled-components]([https://www.styled-components.com/docs/basics#react-native)](https://www.styled-components.com/docs/basics#react-native) "https://www.styled-components.com/docs/basics#react-native)") , I prefer to use styled-components to style my React Native elements the day since I found out that they support React Native it gives me more freedom to make the style I want so easily and you better use [styled-components]([https://www.styled-components.com/docs/basics#react-native)](https://www.styled-components.com/docs/basics#react-native) "https://www.styled-components.com/docs/basics#react-native)") from now and the get the benefits of CSS to make nice UI it makes your code cleaner, you can separate your styles to a single file far from your components that will make your code more organized. in another hand you can use the great features that styled-components provide us such as theming and passing props so you can make a dynamic style like the following:

import React, {Component} from 'react';
import { StyleSheet,Text, View} from 'react-native';
import styled from 'styled-components'
const Container=styled.View`
    flex:1;
    padding:50px 0;
    justify-content:center;
    background-color:#f4f4f4;
    align-items:center
`
const Title=styled.Text`
font-size:20px;
text-align:center;
 color:red;
`
const Item=styled.View`
flex:1;
border:1px solid #ccc;
margin:2px 0;
border-radius:10px;
box-shadow:0 0 10px #ccc;
height:200px;
// execute a specific style based on the props
background-color:${props=>props.transparent?"red":"blue"};
width:80%;
padding:10px;

`
const Shape=styled.View`
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
`

export default class App extends Component {
  render() {
    return (
      <Container>
             <Item transparent>{/*pass the props to the components*/}
             <Title >Item number 1</Title>
             </Item>
             <Item  primary>
             <Title >Item number 1</Title>
             </Item>
             <Item  transparent>
             <Title >Item number 1</Title>
             </Item>
             <Item  primary>
             <Title >Item number 1</Title>
             </Item>
      </Container>
    );
  }
}

And here the result:

So awesome 💪!!

Sometimes you may want to draw some complex shapes that include circles and some specific style or gradient backgrounds for example (CSS gradient background not supported in React Native). you might think of using some methods that CSS provide like clip-path or any other method that allows you to make complex shapes in CSS, unfortunately, those methods are not supported in React Native at this time even if you use styled-components that lets you use the CSS properties into React Native at this situation, we have to use some alternative solutions like using SVG

Using react-native-svg to draw specific shapes

React Native community brings react-native-svg that allows you to use the SVG in React Native. you can add it to your projectusing yarn or npm:

// using yarn

yarn add react-native

// npm 
npm i react-native 

And then make sure to link it by running the following command line:

react-native link react-native-svg

And now let’s start something with it:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 * @lint-ignore-every XPLATJSCOPYRIGHT1
 */

import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";
import styled from "styled-components";
import Svg, {
  Circle,
  Ellipse,
  G,
  TSpan,
  TextPath,
  Path,
  Polygon,
  Polyline,
  Line,
  Rect,
  Use,
  Image,
  Symbol,
  Defs,
  LinearGradient,
  RadialGradient,
  Stop,
  ClipPath,
  Pattern,
  Mask
} from "react-native-svg";

const Container = styled.View`
  flex: 1;
  padding: 50px 0;
  justify-content: center;
  background-color: #f4f4f4;
  align-items: center;
`;
const Title = styled.Text`
  font-size: 20px;
  text-align: center;
  color: red;
`;
const Item = styled.View`
  flex: 1;
  border: 1px solid #ccc;
  margin: 2px 0;
  border-radius: 10px;
  box-shadow: 0 0 10px #ccc;
  height: 200px;
  background-color: ${props => (props.transparent ? "red" : "blue")};
  width: 80%;
  padding: 10px;
`;

export default class App extends Component {
  render() {
    return (
      <Container>
        <Svg height="150" width="300">
          <Defs>
            <LinearGradient id="grad" x1="0" y1="0" x2="170" y2="0">
              <Stop offset="0" stopColor="rgb(255,255,0)" stopOpacity="0" />
              <Stop offset="1" stopColor="red" stopOpacity="1" />
            </LinearGradient>
          </Defs>
          <Ellipse cx="150" cy="75" rx="85" ry="55" fill="url(#grad)" />
        </Svg>

        <Svg height="100" width="100">
          <Defs>
            <RadialGradient
              id="grad"
              cx="50%"
              cy="50%"
              rx="50%"
              ry="50%"
              fx="50%"
              fy="50%"
              gradientUnits="userSpaceOnUse"
            >
              <Stop offset="0%" stopColor="#ff0" stopOpacity="1" />
              <Stop offset="100%" stopColor="#00f" stopOpacity="1" />
            </RadialGradient>
            <ClipPath id="clip">
              <G scale="0.9" x="10">
                <Circle cx="40" cy="30" r="20" />
                <Ellipse cx="60" cy="70" rx="20" ry="10" />
                <Rect x="65" y="15" width="50" height="50" />
                <Polygon points="20,60 20,80 50,70" />
                <Text
                  x="50"
                  y="30"
                  fontSize="32"
                  fonWeight="bold"
                  textAnchor="middle"
                  scale="1.2"
                >
                  Q
                </Text>
              </G>
            </ClipPath>
          </Defs>
          <Rect
            x="0"
            y="0"
            width="100"
            height="100"
            fill="url(#grad)"
            clipPath="url(#clip)"
          />
        </Svg>
        <Svg height="100" width="300">
          <Defs>
            <G id="shape">
              <G>
                <Circle cx="50" cy="50" r="50" />
                <Rect x="50" y="50" width="60" height="50" />
                <Circle cx="50" cy="50" r="5" fill="#c00" />
              </G>
            </G>
          </Defs>
          <Use href="#shape" x="20" y="0" />
          <Use href="#shape" x="170" y="0" />
        </Svg>
      </Container>
    );
  }
}

Examples from react-native-svg docs](https://github.com/react-native-community/react-native-svg#clippath) "https://github.com/react-native-community/react-native-svg#clippath)")

The examples above are from react-native-svg docs](https://github.com/react-native-community/react-native-svg) "https://github.com/react-native-community/react-native-svg)")

As you see you can go so far with react-native-svg in making specific shapes and gradient backgrounds and the things you usually do with SVG. you can check the official docs to see the available options.

Wrapping up

You can still use the React Native style method to make what you need but it remains complex when we want to make some complex styles so you need to use some alternative tools like react-native-svg to do that, for normal styling I like to use styled components it makes doing things easier for me and I hope the React Native community bring more supports of other style methods that will give us the freedom of making things easily

react-native

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...

Build a simple React Native Pokemon app with React-Navigation

As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology.

Hire Dedicated React Native Developer in India | React Native Development

Hire dedicated React Native developers for your next project. As the top react native development company we offer you the best service as per your business needs.

Top React Native Mobile App Development Companies in USA

Looking for top React Native mobile app development company in USA for Startups & Enterprise? Find out the top list of React Native mobile app development company in USA.

Which Kind of Apps Are Most Suitable for React Native? - TopDevelopers.co

React Native is beneficial to develop custom mobile apps and in addition to that the cross-platform app development framework is best suited for the apps of various types.