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.
With 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 will be using the expo-cli to bootstrap the new project. If you already have an existing React Native project, skip straight to the Installing styled-components
step.
npx expo-cli init [Project Name] cd [Project Name]
Move into your project’s directory, then run any of the following commands.
# with npm npm install --save styled-components # with yarn yarn 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';
With styled-components, you are able to define 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
This means that you can give a component a primary state that is set to true when passed:
const StyledText = styled.Text` padding: ${props => props.pad ? '5px' : 0}; ` //usage return ( <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}; ` //usage return ( <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> ); }
Note: You cannot use
keyframes
andcreateGlobalStyle
helpers while styling as React Native does not support keyframes or global styles.
RELATED TAGS
CONTRIBUTOR
View all Courses