Styled-components is a CSS-in-JavaScript library that allows you to use component-level styles in your application. It is easy to maintain, and saves you the stress of remembering, duplicating, or misspelling class names.
React Native is an open-source mobile application framework.
Using styled components, you can build simple, dynamic, and reusable components by writing CSS in your React Native component.
First, you need to create a React Native project. I would be using the
npx expo-cli init [Project Name]cd [Project Name]
Move into your project’s directory then run any of the following commands.
# with npmnpm install --save styled-components# with yarnyarn add styled-components
This command installs the latest version of styled-components on your project.
You need to import styled-components library in the file where it is would be used.
import styled from 'styled-components/native';
By using styled-components, you are defining your styles by creating a new component from an already existing component. For example, you can create a Layout
component that inherits properties from React Native’s View
component.
const Layoyt = styled.View`flex: 1;background-color: #B0E0E6;align-Items: 'center';justify-content: 'center';`
props
Based AdaptationAccording to the styled-component documentation, you can pass a function (“interpolations”) to a styled component’s template literal to adapt it based on its props.
This means that you can give a component a primary state which is set to true when passed,
const StyledText = styled.Text`padding: ${props => props.pad ? '5px' : 0};`//usagereturn (<StyledText pad>Styled React Native.</StyledText>//this text would have a 5px padding around it)
or, props can be passed to the mounted DOM node.
const StyledText = styled.Text`font-size: ${props => props.font};`//usagereturn (<StyledText pad font='18px'>Styled React Native.</StyledText>//this text would have a 5px padding around it// a font size of 18px)
import React from 'react';import { Text, View, TouchableOpacity } from 'react-native';import styled from 'styled-components/native'const Layoyt = styled.View`flex: 1;background-color: #B0E0E6;align-Items: 'center';justify-content: 'center';`const StyledText = styled.Text`font-size: ${props => props.font};color: #11040a;padding: ${props => props.pad ? '5px' : 0};`const ButtonEffect = styled.TouchableOpacity`background-color: #eeafcf;padding: 10px;`export default function App() {return (<Layoyt><StyledText font='18px' pad>Styled React Native.</StyledText><ButtonEffect><StyledText font='14px'>Press Me</StyledText></ButtonEffect></Layoyt>);}
NB: You cannot use
keyframes
andcreateGlobalStyle
helpers while styling as React Native does not support keyframes or global styles.