Home > Mobile >  How to style nativewind element with multiple custom styles
How to style nativewind element with multiple custom styles

Time:02-02

I want to style a component with my own custom className that has certain properties. Tailwind lets you do this through App.css, but in a react native application there is none. How do you add say a '.title' class to tailwind with certain properties?

.title {
    font-size: 24px
    font-weight: 800
}

Applying it to Text JSX object:

<Text className="title">Title Text!</Text>

CodePudding user response:

I figured out this method of styling multiple of the same components. Nativewind and Tailwind suggest not using this method, but it works for both.

In your tailwind.config.js file, add the following line of code above your module.exports:

const plugin = require("tailwindcss/plugin");

module.exports = {...}

Then in your plugins list, add:

plugin(function ({ addComponents }) {
        addComponents({
            ".title": {
                fontWeight: 800,
                fontSize: 24,
            },
        });
    }),

Make sure your styling uses the same property names as react-native, and NOT css (fontWeight vs font-weight). Restart your server, and it should work!

CodePudding user response:

You can use twrnc npm package for this. Install it from here.

Import it like this in the file at the top.

import tw from "twrnc";

And use it like this

<Text style={tw` text-2xl font-extrabold`}>Title Text!</Text>
  • Related