Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

tailwind-react-native-classnames

> 编程语言
Open source

simple, expressive API for tailwindcss + react-native

2.4K stars0 likes1 views
WebsiteGitHub

About

simple, expressive API for tailwindcss + react-native

Tailwind React Native Classnames ‍♂️

A simple, expressive API for TailwindCSS + React Native, written in TypeScript

javascript
import { View, Text } from 'react-native';
import tw from 'twrnc';

const MyComponent = () => (
  <View style={tw`p-4 android:pt-2 bg-white dark:bg-black`}>
    <Text style={tw`text-md text-black dark:text-white`}>Hello World</Text>
  </View>
);

Features

  • full support for all native RN styles with tailwind counterparts: (view, layout, image, shadow, and text).
  • very fast: best performance of all RN styling libraries, according to this benchmark.
  • compatible with Tailwind CSS v3 and v2
  • respects your tailwind.config.js for full configuration
  • platform prefixes: android:mt-4 ios:mt-2
  • dark mode support: bg-white dark:bg-black
  • media query support: w-48 lg:w-64 (also, arbitrary: min-w-[600px]:flex-wrap)
  • device orientation prefixes: portrait:flex-col landscape:flex-row
  • vw and vh unit support: h-screen, min-w-screen, w-[25vw], etc...
  • retina device pixel density prefix: w-4 retina:w-2
  • arbitrary, JIT-style classes: mt-[31px] bg-[#eaeaea] text-red-200/75, etc...
  • tagged template literal syntax for most common usage
  • merges supplied RN style objects for unsupported utilities or complex use cases
  • supports custom utility creation via standard plugin config.
  • flexible, conditional styles based on classnames package api.
  • written 100% in TypeScript, ships with types

Docs:

  • Installation
  • API
  • Customization
  • Enabling Device-Context Prefixes
  • Taking Control of Dark Mode
  • Customizing Breakpoints
  • Adding Custom Classes
  • Matching Conditional Prefixes
  • Box-Shadows
  • RN-Only Additions
  • JIT-style Arbitrary Values
  • VS Code Intellisense
  • JetBrains IDEs Intellisense
  • Memo-Busting
  • Migrating from previous versions
  • Prior Art

Installation

bash
npm install twrnc

API

The default export is an ES6 Tagged template function which is nice and terse for the most common use case -- passing a bunch of space-separated Tailwind classes and getting back a react-native style object:

javascript
import tw from 'twrnc';

tw`pt-6 bg-blue-100`;
// -> { paddingTop: 24, backgroundColor: 'rgba(219, 234, 254, 1)' }

In the spirit of Tailwindcss's intuitive responsive prefix syntax, twrnc adds support for platform prefixes to conditionally apply styles based on the current platform:

javascript
//  styles only added if platform matches
tw`ios:pt-4 android:pt-2`;

Media query-like breakpoint prefixes supported (see Breakpoints for configuration):

javascript
//  faux media queries
tw`flex-col lg:flex-row`;

Dark mode support (see here for configuration);

javascript
//  dark mode support
tw`bg-white dark:bg-black`;

You can also use tw.style() for handling more complex class name declarations. The api for this function is directly taken from the excellent classnames package.

…

If you need some styling that is not supported in a utility class, or just want to do some custom run-time logic, you can pass raw RN style objects to tw.style(), and they get merged in with the styles generated from any other utility classes:

javascript
tw.style(`mt-1`, {
  resizeMode: `repeat`,
  width: `${progress}%`,
});
// -> { marginTop: 4, resizeMode: 'repeat', width: '32%' }

The tw function also has a method color that can be used to get back a string value of a tailwind color. Especially useful if you're using a customized color palette.

javascript
tw.color('blue-100'); // `bg|text|border-blue-100` also work
// -> "rgba(219, 234, 254, 1)"

You can import the main tw function and reach for tw.style only when you need it:

javascript
import tw from 'twrnc';

const MyComponent = () => (
  <View style={tw`bg-blue-100`}>
    <Text style={tw.style('text-md', invalid && 'text-red-500')}>Hello</Text>
  </View>
);

...or if the tagged template function isn't your cup of tea, just import tw.style as tw:

javascript
import { style as tw } from 'twrnc';

const MyComponent = () => (
  <View style={tw('bg-blue-100', invalid && 'text-red-500')}></View>
);

Customization

You can use twrnc right out of the box if you haven't customized your tailwind.config.js file at all. But more likely you've got some important app-specific tailwind customizations you'd like to use. For that reason, we expose the ability to create a custom configured version of the tw function object.

javascript
// lib/tailwind.js
import { create } from 'twrnc';

// create the customized version...
const tw = create(require(`../../tailwind.config.js`)); // <- your path may differ

// ... and then this becomes the main function your app uses
export default tw;

...and in your component files import your own customized version of the function instead:

javascript
// SomeComponent.js
import tw from './lib/tailwind';

[!note] If you are using export default {} in your tailwind.config.js file, you need to pass the default to create util from your config require: require('../../tailwind.config.js').default.

Enabling Device-Context Prefixes

To enable prefixes that require runtime device data, like dark mode, and screen size breakpoints, etc., you need to connect the tw function with a dynamic source of device context information. The library exports a React hook called useDeviceContext that takes care of this for you. It should be included one time, at the root of your component hierarchy, as shown below:

javascript
import tw from './lib/tailwind'; // or, if no custom config: `from 'twrnc'`
import { useDeviceContext } from 'twrnc';

export default function App() {
  useDeviceContext(tw); // <- 
  return (
    <View style={tw`bg-white dark:bg-black`}>
      <Text style={tw`text-black dark:text-white`}>Hello</Text>
    </View>
  );
}

⚠️ If you're using Expo, make sure to make the following change in app.json to use the dark: prefix as Expo by default locks your app to light mode only.

json
{
  "expo": {
    "userInterfaceStyle": "automatic"
  }
}

Taking Control of Dark Mode

By default, if you use useDeviceContext() as outlined above, your app will respond to ambient changes in the device's color scheme (set in system preferences). If you'd prefer to explicitly control the color scheme of your app with some in-app mechanism, you'll need to configure things slightly differently:

…

Customizing Breakpoints

You can customize the breakpoints in the same way as a tailwindcss web project, using tailwind.config.js. The defaults that ship with tailwindcss are geared towards the web, so you likely want to set your own for device sizes you're interested in, like this:

javascript
// tailwind.config.js
module.exports = {
  theme: {
    screens: {
      sm: '380px',
      md: '420px',
      lg: '680px',
      // or maybe name them after devices for `tablet:flex-row`
      tablet: '1024px',
    },
  },
};

Adding Custom Classes

To add custom utilities, use the plugin method described in the tailwind docs, instead of writing to a .css file.

javascript
const plugin = require('tailwindcss/plugin');

module.exports = {
  plugins: [
    plugin(({ addUtilities }) => {
      addUtilities({
        '.btn': {
          padding: 3,
          borderRadius: 10,
          textTransform: `uppercase`,
          backgroundColor: `#333`,
        },
        '.resize-repeat': {
          resizeMode: `repeat`,
        },
      });
    }),
  ],
};

Wil also allow you to supply a string of other utility classes (similar to @apply), instead of using CSS-in-JS style objects:

javascript
module.exports = {
  plugins: [
    plugin(({ addUtilities }) => {
      addUtilities({
        //  similar to `@apply`
        '.btn': `px-4 py-1 rounded-full bg-red-800 text-white`,
        '.body-text': `font-serif leading-relaxed tracking-wide text-gray-800`,
      });
    }),
  ],
};

Matching Conditional Prefixes

twrnc also exposes a tw.prefixMatch(...prefixes: string[]) => boolean function that allows you to test whether a given prefix (or combination of prefixes) would produce a style given the current device context. This can be useful when you need to pass some primitive value to a component, and wish you could leverage tw's knowledge of the current device, or really anywhere you just need to do some logic based on the device context. This could also be accomplished by importing Platform or a combination of other RN hooks, but chances are you've already imported your tw function, and this saves you re-implementing all that logic on your own:

typescript
const SomeComponent = () => (
  <View>
    <Thumbnail imageSize={tw.prefixMatch(`portrait`) ? 60 : 90} />
    {tw.prefixMatch(`ios`, `dark`) ? <CustomIosDarkModeThing /> : <Thing />}
  </View>
);

Box Shadows

Box shadows in CSS differ substantially from shadow in RN, so this library doesn't attempt to parse CSS box-shadow strings and translate them into RN style objects. Instead, it offers a number of low-level utilities not present in tailwindcss, which map to the 4 shadow props in RN:

…

We also provide a default implementation of the shadow-<X> utils provided by tailwindcss, so you can use:

javascript
tw`shadow-md`;
/*
-> {
  shadowOffset: { width: 1, height: 1 },
  shadowColor: `#000`,
  shadowRadius: 3,
  shadowOpacity: 0.125,
  elevation: 3,
}
*/

To override the default implementations of these named shadow classes, add your own custom utilities -- any custom utilities you provide with the same names will override the ones this library ships with.

RN-Only Additions

twrnc implements all of the tailwind utilities which overlap with supported RN (native, not web) style props. But it also adds a sprinkling of RN-only utilities which don't map to web-css, including:

  • low-level shadow utilities
  • elevation (Android only), eg: elevation-1, elevation-4
  • small-caps -> {fontVariant: 'small-caps'}
  • number based font-weight utilities font-100, font-400, (100...900)
  • direction-(inherit|ltr|rtl)
  • align-self: baseline; via self-baseline
  • include-font-padding and remove-font-padding (Android only: includeFontPadding)
  • image tint color control (tint-{color} e.g. tint-red-200)
  • pointer-events-(box-only|box-none)

JIT-Style Arbitrary Values

Many of the arbitrary-style utilities made possible by Tailwind JIT are implemented in twrnc, including:

  • arbitrary colors: bg-[#f0f], text-[rgb(33,45,55)]
  • negative values: -mt-4, -tracking-[2px]
  • shorthand color opacity: `te

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言