Unlock the Power of CSS-in-JS in React Native
The rise of component-based libraries and frameworks like React, Angular, and Vue has revolutionized the way we approach CSS styling. One of the most popular techniques to emerge from this shift is CSS-in-JS, which allows us to compose CSS using JavaScript and abstract styles to the component level.
What is CSS-in-JS?
CSS-in-JS enables us to solve common CSS problems, such as name collision, and use normal CSS naming conventions instead of camelCase. It also provides additional benefits when used with library integrations like styled-components, particularly for mobile apps.
Getting Started with Styled Components and Styled System
To follow along, you’ll need a working knowledge of CSS, React, and React Native. Let’s create a new React Native application using Expo CLI and install the necessary dependencies.
Building a Styled React Native Application
We’ll start by adding style props to React components using Styled System. This library provides a set of functions that add style props to our components, allowing us to rapidly prototype our UI.
Creating Reusable Components
By creating reusable components with Styled System, we can provide each component with access to the necessary style props passed to it by the style functions. This makes our code clean, DRY, and easy to maintain.
Styling Our Layout
Let’s put everything together by building a Notification layout. We’ll create a components folder with three files: Notifications.js, Card.js, and Text.js. Each file will contain code that adds style props to our components.
Theming with Styled System
Styled System also supports the use of themes, which allows us to create a consistent and maintainable styling approach. We’ll create a theme.js file that holds an object defining all our styles and use it with the ThemeProvider provided via context by most CSS-in-JS libraries.
The Benefits of Styled System
Styled System is a revolutionary way of styling React Native components that uses a simple approach. It allows us to rapidly prototype our UI, works with several CSS-in-JS libraries like styled-components, and provides a consistent and maintainable styling approach. Give it a try on your next project!