Conditional styling in React Native (styled components)
One of the most useful tricks I learned when I started styling screens in React Native was how to conditionally apply CSS to a container.
Some of the most common use cases were reusing a component in a context where it has a slightly different style, display bottom border to all elements in a list except the last element, change input style on focus etc.
Now, let’s look at an example together.
Photo source: https://www.freepik.com/
Firstly, run npx create-expo-app styling-app to create a new Expo project. Next, let’s cd into styling-app and install styled components:
npm install --save styled-components
#or
yarn add styled-components
Finally, open the app in your favorite code editor and run it. If you want to change a single style property you can pass a prop to a container and conditionally apply a style, depending on that prop.
import { Text } from 'react-native';
import styled from "styled-components/native";
export default function App() {
return (
<DashboardContainer>
<Text>Register to your recycling account today!</Text>
<ButtonContainer isMain={true}><Text>Continue</Text></ButtonContainer>
<ButtonContainer><Text>Go back</Text></ButtonContainer>
</DashboardContainer>
);
}
const DashboardContainer = styled.View`
flex: 1;
alignItems: center;
justifyContent: center;
`
const ButtonContainer = styled.TouchableOpacity`
padding: 8px;
margin-vertical: 6px;
border-radius: 4px;
background-color: ${({isMain}) => isMain? '#93D976': '#F2F2F2' }
`
As you can see in the example above, I pass isMain prop to the ButtonContainer and if isMain is a truthy value the background color is green, otherwise it changes to gray. Here's how our buttons should look:
In case you need to render multiple stylings you can use template literals:
const ButtonContainer = styled.TouchableOpacity`
padding: 8px;
margin-vertical: 6px;
border-radius: 4px;
${({ isMain }) =>
isMain && `
background-color: #93D976;
border-color: #013220;
border-width: 1px;
`}
`
Or if you use TypeScript, you can type check the prop:
const ButtonContainer = styled.TouchableOpacity<{isMain: boolean}>`
padding: 8px;
margin-vertical: 6px;
border-radius: 4px;
${({ isMain }) =>
isMain && `
background-color: #93D976;
border-color: #013220;
border-width: 1px;
`}
`
Still curious to learn more about how styled components work? Check styled components documentation. Good luck! 🚀
#2Articles1Week, #Hashnode
Subscribe to my newsletter
Read articles from Lavinia Ţole directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Lavinia Ţole
Lavinia Ţole
🚀 Software Engineer 📚 Lifelong learner