How to use Tailwind CSS in React Native

sasicodes

Sasidharan

Posted on October 15, 2021

How to use Tailwind CSS in React Native

Styling in React Native is pretty simple at the initial stage when we are developing a new application. React Native's Stylesheet helps us to add styles to our elements. When the codebase increases, stylesheets (both external/internal) will be increased, and so maintaining the uniform class names, reusing styles is a nightmare.

Tailwind CSS is an open-source utility-first CSS framework. It redefines the way you style applications by providing a variety of CSS classes by default and we can customize to any extend. Without writing custom styles for each element back and forth, we can use tailwind to write inline styles effectively. It gives a solid design system by default and helps writing conditional , device-specific styles are the major advantages. By this approach, bulk stylesheets will be reduced and can reuse tailwind styles to other components.

Personally, am not a big fan of writing complete CSS on my own, this [lagandlog.com] is completely built using tailwindcss and I had a great experience and it came out really well. The bundle size of the tailwind is <10KB and it is super ok✌️

Where to start?

Many packages out there were mainly created to use TailwindCSS in React Native. Every package has its own way of usage and we are not gonna learn each of them. Listing few useful dependencies below for reference,

These packages were simple to use and will not replace any native components.

Which one to use?

Each one of them is similar and has its own advantages, please refer to the official documentation and find the one that suits you.

Note: TailwindCSS is not created specifically to React Native, so some of the class names will not be supported.

We are trying something more useful, device-specific customizable package tailwind-react-native-classnames.

Installation

npm install tailwind-react-native-classnames
Enter fullscreen mode Exit fullscreen mode

Usage

import { View, Text } from 'react-native';
import tw from 'tailwind-react-native-classnames';

const MyComponent = () => (
  <View style={tw`p-4 android:pt-2 bg-red-300 flex-row`}>
    <Text style={tw`text-md tracking-wide`}>Hey there!</Text>
  </View>
);
Enter fullscreen mode Exit fullscreen mode

Platform-specific styles

// 😎 styles only added if platform matches
tw`ios:pt-4 android:pt-2`;
Enter fullscreen mode Exit fullscreen mode

You can learn more about customizing, overwriting, configurations of the package here.

Sample Design

tailwind-rn.pngImage Source - tailwind-rn

Hope this log is useful for you, feel free to add your thoughts in the comments.

TailwindCSS Cheatsheet - https://nerdcave.com/tailwind-cheat-sheet

Follow me on Twitter

Happy Coding!

💖 💪 🙅 🚩
sasicodes
Sasidharan

Posted on October 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related