Coder Social home page Coder Social logo

tailwind-rn's Introduction


tailwind-rn Status

Use Tailwind in React Native projects

All styles are generated directly from Tailwind's output, so they're always up-to-date.

  • JIT mode
  • Responsive breakpoints (e.g. sm, md, lg)
  • Dark mode
  • Custom configuration

Migrating from v3.x?


Install

$ npm install tailwind-rn

Getting Started

Run the following command to automatically add tailwind-rn to your React Native project:

$ npx setup-tailwind-rn

It will do most of the setup for you, but you'll have to follow a few more instructions from setup-tailwind-rn to finish the process.

Manual setup
  1. Install tailwind-rn.
$ npm install tailwind-rn
  1. Install Tailwind and concurrently.
$ npm install --save-dev tailwindcss postcss concurrently
  1. Create Tailwind config and necessary files.
$ npx tailwindcss init
$ echo '@tailwind utilities;' > input.css

These commands will create the following files:

  • tailwind.config.js - Tailwind configuration file.
  • input.css - Entrypoint for Tailwind compiler. It's required to override the output of Tailwind, so that it doesn't generate CSS for resetting browser styles, which will cause tailwind-rn to fail.

Disable unsupported utilities by adding this line to your tailwind.config.js:

module.exports = {
+	corePlugins: require('tailwind-rn/unsupported-core-plugins')
};

Make sure to configure content part of the config in tailwind.config.js to point to your JavaScript files to speed up compilation.

  1. Add scripts to build Tailwind styles in package.json.
{
	"scripts": {
+		"build:tailwind": "tailwindcss --input input.css --output tailwind.css --no-autoprefixer && tailwind-rn",
+		"dev:tailwind": "concurrently \"tailwindcss --input input.css --output tailwind.css --no-autoprefixer --watch\" \"tailwind-rn --watch\""
	}
}
  1. Build Tailwind styles in watch mode.
$ npm run dev:tailwind

After styles are built, you'll see two more files:

  • tailwind.css - CSS generated by Tailwind.
  • tailwind.json - The same CSS, but converted into JSON, so that tailwind-rn can understand it.
  1. Import TailwindProvider and tailwind.json in the root of your app and wrap the root of your app with it:
import {TailwindProvider} from 'tailwind-rn';
import utilities from './tailwind.json';

const App = () => (
	<TailwindProvider utilities={utilities}>
		<MyComponent />
	</TailwindProvider>
);

export default App;
  1. Use Tailwind in React Native!
import {useTailwind} from 'tailwind-rn';

const MyComponent = () => {
	const tailwind = useTailwind();

	return <Text style={tailwind('text-blue-600')}>Hello world</Text>;
};

Usage

Use useTailwind React hook and apply any of the supported utilities from Tailwind in your React Native views.

import React from 'react';
import {SafeAreaView, View, Text} from 'react-native';
import {useTailwind} from 'tailwind-rn';

const Hello = () => {
	const tailwind = useTailwind();

	return (
		<SafeAreaView style={tailwind('h-full')}>
			<View style={tailwind('pt-12 items-center')}>
				<View style={tailwind('bg-blue-200 px-3 py-1 rounded-full')}>
					<Text style={tailwind('text-blue-800 font-semibold')}>
						Hello Tailwind
					</Text>
				</View>
			</View>
		</SafeAreaView>
	);
};

export default Hello;

tailwind function returns a simple object with styles, which can be used in any React Native view, such as <View>, <Text> and others.

tailwind('pt-12 items-center');
//=> {
//     paddingTop: 48,
//     alignItems: 'center'
//   }

CLI

$ tailwind-rn --help

  Use Tailwind CSS in React Native projects

  Usage
    $ tailwind-rn [options]

  Options
    -i, --input    Path to CSS file that Tailwind generates (default: tailwind.css)
    -o, --output   Output file (default: tailwind.json)
    -w, --watch    Watch for changes and rebuild as needed

Run tailwind-rn CLI to transform the CSS generated by Tailwind into a JSON file that can be consumed by TailwindProvider. Add --watch flag to watch for changes and build styles continuously, which is useful for development.

API

TailwindProvider

utilities

Type: object

Parsed JSON object of styles generated by tailwind-rn CLI stored in tailwind.json by default.

import {TailwindProvider} from 'tailwind-rn';
import utilities from './tailwind.json';

const App = () => (
	<TailwindProvider utilities={utilities}>
		<MyComponent />
	</TailwindProvider>
);

colorScheme

Type: string

Override the default color scheme. Possible values are light or dark.

import {TailwindProvider} from 'tailwind-rn';
import utilities from './tailwind.json';

const App = () => (
	<TailwindProvider utilities={utilities} colorScheme="dark">
		<MyComponent />
	</TailwindProvider>
);

useTailwind

React hook, which returns a tailwind function, that accepts a string with class names. This function returns an object of styles, which can be applied to a React Native view via style property.

Note: Add TailwindProvider above the component where you're using this hook.

import {useTailwind} from 'tailwind-rn';

const MyComponent = () => {
	const tailwind = useTailwind();

	return <Text style={tailwind('text-blue-600')}>Hello world</Text>;
};

Supported Utilities

Modifiers

Layout

Flexbox

Spacing

Sizing

Typography

Backgrounds

Borders

Effects

Interactivity

tailwind-rn's People

Contributors

benmurden avatar catalinmiron avatar dakshshah96 avatar dependabot-preview[bot] avatar eduludi avatar inerds avatar jericopulvera avatar timbastin avatar vadimdemedes avatar xico2k avatar yarkhan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tailwind-rn's Issues

Unsupported Tailwind Class for colors / getColor

Hello,

I've been testing out this library and running into one peculiar issue.

I have defined a custom tailwind config and npx create-tailwind-rn creates a styles.json without complaint. Within the styles json I see that all the derived component color classes (bg-red-100, text-green-200 etc) based off my custom colors are created but the actual color classes I would use with getColor (eg getColor('green-200'))) do not appear. When I try to use getColor the app warns "unsupported tailwind class" for any color I try. Am I missing something to get the color classes showing in styles/ callable via getColor?

Thanks in advance for any help!

Module Resolution Error when importing in an Expo project

I got this error just by importing tailwind-rn:

Internal Error Metro has encountered an error: While trying to resolve module tailwind-rn from file App.js, the package node_modules/tailwind-rn/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (node_modules/tailwind-rn/index

Background steps not working

style={tailwind( "flex flex-col justify-center items-center bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 min-h-full w-full " )}

I get all the different bg gradient classes as an unsupported warning, any ideas?

[Question] How to use shadows?

Hey! Thanks a lot for the awesome package! I was just migrating my app to it, but I've run into some problem with shadows, when trying to use the class apparently it is not supported, is there any way to use it?

tailwindcss 2.0 requires postcss 8 and tailwind-rn is using postcss 7

everytime I try to use npx creaate-tailwind-rn I get this error:

/node_modules/tailwind-rn/node_modules/postcss/lib/processor.js:153
        throw new Error('PostCSS plugin ' + plugin.postcssPlugin + ' requires PostCSS 8.\n' + 'Migration guide for end-users:\n' + 'https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users');
        ^

Error: PostCSS plugin tailwindcss requires PostCSS 8.

Mix tailwind and basic style

Hi, thanks for this great package, it is possible to mix tailwind and basic style like that ?

style={
    (tailwind("bg-gray-800 flex-row items-center py-6")),
    { backgroundColor: global.currentScreenIndex === key ? textCurrent : textNotCurrent }
}

Is there a way to use grid?

First of all - thank you for this great package! I was trying to use grid class today, but it seems it is not supported (yet).

Is there is a way to use it, or are you planning to add this functionality? Thanks.

Tailwind UI usage

Hey, thanks for this awesome library. Out of curiosity, does this work with Tailwind UI?

I'm new to the Tailwind ecosystem so I'm trying to understand how it all works together. I know that I'd have to change the Tailwind UI HTML to react native primitives, but assuming I did that, would it work?

Tailwind 2.0

Hi! Love your project!
Since tailwind 2.0 is out, any plans to upgrade to 2.0?

Border radius issues

When I use rounded-lg for example I expect my button to have all 4 rounded corners on iOS and Android but since it's translated to this:

...
  "rounded-lg": {
    "borderTopLeftRadius": 8,
    "borderTopRightRadius": 8,
    "borderBottomRightRadius": 8,
    "borderBottomLeftRadius": 8
  }
...

I think that since the specific corner radius is not well supported on iOS, there is a problem with translating it to that when you are applying the same border radius to all corners.

npm registry not found

Screen Shot 2020-09-28 at 11 58 54 PM

Can anybody please help why am I getting above error after running npx create-tailwind-rn

Support space utilities from Tailwind CSS

Hi there, first of all thank you for this lib, it is really convenient for people who like to use tailwind like me.

For new tailwind version, I really missed some feature like https://tailwindcss.com/docs/space#app, which is very save a lot of unessential codes to add margin between components in flex.

So do you guys have plan to update new version of tailwind for this package.

Using any tracking property on android causes the app to close without an error

Using the tracking class on android (SDK version 28) causes the app to close without error, I imagine it could be because letter spacing only supports numeric values but in the styles.json file the value is an em

If I could see how the styles.json was generated I'd be happy to submit a PR to fix

Really enjoying using this lib so far thanks!

Unsupported Tailwind Class ""

This happens when writing multi-line classes or just having additional space in between class names.

Is there a way to fix this?

    <TouchableOpacity
      style={{
        ...tailwind(`
            px-6 
            py-2 
            self-start 
            mr-2 
            ${selectedOptions[option.name] === value.name ? 'bg-teal-500' : 'bg-gray-300'}
        `),
      }}>
          {value.name}
      </TouchableOpacity>

Custom Colors & Fonts not showing up in styles.json

I followed the instructions in the readme. The fonts and colors are not showing up in the styles.js.

tailwind.config.js

module.exports = {
	purge: [],
	theme: {
		fontFamily: {
			josefin: ["Josefin"],
			roboto: ["Roboto"],
			bebas_neue: ["BebasNeue"],
			anton: ["Anton"],
		},
		extend: {
			colors: {
				primary: "#070d13",
				secondary: "#222933",
				accent: "#42505e",
			},
		},
	},
	variants: {},
	plugins: [],
};

tailwind.js

import { create } from "tailwind-rn";
import styles from "./styles.json";

const { tailwind, getColor } = create(styles);
export { tailwind, getColor };

Support breakpoints for responsive design

Understandably, on mobile, breakpoints are not super relevant.

However, RN can "go back to the web" using react-native-web, which is now baked into Expo managed workflows.

Currently, you must combine a design system or library or "roll your own" to get responsive breakpoint support in RN.

Having breakpoints carry over to Tailwind-RN (from vanilla Tailwind) would be helpful for anyone trying to write an app in a single codebase, and it would avoid having to use more design systems and libraries on top of Tailwind.

Support custom Tailwind config

I created custom config with colors like grey-900 but they where removed from styles.json.
I found this line in build.js /^bg-(transparent|black|white|gray|red|orange|yellow|green|teal|blue|indigo|purple|pink)/
I think it should be like this /^bg-/

Support @apply

Hello,

I love the idea of this project! I was wondering if @apply is something this library can support? I am working on my own internal "css framework" which works something like this:

.button {
  @apply py-2 px-2 text-uppercase...
}

.button-blue {
  @apply bg-blue-500
}

I was wondering if this library could somehow ingest this kind of file and then convert button to its associated styles (and ignore whatever react native doesn't support)?

Tailwind config

Is it possible to use tailwind config?
eg: to create custom color palette?

npx create-tailwind-rn throwing 404 error

I've installed tailwind-rn and I'm trying to create the styles.json file using npx create-tailwind-rn but I get this error

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/create-tailwind-rn - Not found
npm ERR! 404 
npm ERR! 404  'create-tailwind-rn@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)  
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

Using numerous libraries that are deprecated or outright broken

Hey, I noticed when installing that there were numerous libraries you're using that are unsupported, deprecated, and in some cases simply will not work on newer versions of node or when combined with other newer libraries.

Now I usually see a few deprecated, that's just a given, but there's probably a dozen here and some of the libraries are screaming "Don't use me! I will break your program!"

Suggested updating at least the most severe dependency issues

pseudo selectors

Hey! I have been using tailwind-rn for a project recently and developed this pattern and thought I would socialize it to get some feedback.

The idea here is to introduce psudo-selectors to tailwind-rn. Due to not being able to hook in very well to RN apis, I pass in the needed data as a second arg, an object of string keys with bool values to toggle the selectors. It supports single and multiple selectors just like tailwind supports.

The downside of my first stab at this is it is all runtime calculated, and it will make it hard to tyle the utility classes. As a result, I am trying some other options, that said, I will say the DX of this has been, in my opinion, really nice for making components with tailwind.

for example:

const tailwindProps = {
    disabled: disabled || !onPress,
    fullWidth: fullWidth,
    primary: varient === "primary",
    secondary: varient === "secondary",
    hasText: !!text,
};

// then later in my component, styling with...

 tailwind( `
    primary:bg-indigo-500 
    primary:border-indigo-600 
    primary:disabled:bg-gray-500

    secondary:bg-gray-200 
    secondary:border-gray-400 
    secondary:disabled:bg-white 
    secondary:disabled:border-gray-500

    fullWidth:w-full
    hasText:py-4
    border items-center justify-center rounded-md flex-row`,
    tailwindProps
)

This is accomplished by composing my typescript function like so:

import { create } from 'tailwind-rn';
import styles from '../assets/tw-styles.json';
const { tailwind, getColor } = create(styles);

type Selectors = Partial<{
    focus: boolean,
    disabled: boolean
    sm: boolean
    md: boolean
    lg: boolean
    [selector: string]: boolean
}>

const t = (styles: string, selectors?: Selectors) => {

    const cleanStyles = styles.replace(/\s\s+/g, ' ').trim()
    return {
        ...(selectors ? mapFromStyles(cleanStyles, selectors) : tailwind(cleanStyles)),
    }
}

const mapFromStyles = (styles: string, selectors: Selectors) => {
    const classes = styles.split(' ');
    const usedClasses = classes.filter(c => {
        if (!c.includes(':')) return true

        const psudos = c.split(':').slice(0, -1) as Array<keyof Selectors>;
        return psudos.map(p => selectors[p]).filter(v => v).length >= psudos.length
    }).sort((a, b) => {
        // the more matched selectors, the more exact match, make it last so it overides the previos options
        return (a.split(":").length - 1) - (b.split(":").length - 1);
    }).map(c => c.split(':').pop()).join(' ');

    return tailwind(usedClasses)
}

export { t as tailwind, t, getColor, mapFromStyles };

Responsive not working

Hi @vadimdemedes

Nice package!

But the following is not working:
``<View style={tailwind('w-1/3 sm:w-full items-center')}>```

Expected that the react-native app on sm: was full width and otherwise 1/3'th width..

Letter spacing is not supported

To reproduce, simply create a new Text element with tracking-tighter class:

<Text
   style={tailwind(
     'tracking-widest'
   )}>
  Hello World!
</Text>

And you'll have the following error:

Warning: Failed prop type: Invalid prop `letterSpacing` of type `string` supplied to `Text`, expected `number`.
Bad object: {
  "letterSpacing": "0.1em"
}

I can create a PR to update the README to update the supported utilities, just let me know. If you have troubles reproducing the issue, I would be happy to help also.

Workaround: customize tailwind config and override value in px.

Max

Any ideas on how to support Theming ?

First of all thanks for making such an awesome library, really love using Tailwind everywhere ๐Ÿ˜ƒ

I'm going to start work on a new app, but it would require theming. Are there any pointers on how to support user switchable themes using this library?

I thought about creating a separate function that wraps the tailwind function and which then would replace bg-primary with the current selected theme, but that seems error-prone. Any suggestions are welcome.

I found this library https://www.npmjs.com/package/rn-themed-tailwind but it is nowhere near as mature as this one.

[Proposal] create production and development version

My proposal is to separate tailwind-rn into two versions:

Development

This version will allow us to give error messages and warnings.

Production

While the production version will remain only with the business logic.

An example of this is the following code; which is unnecessary in the production version.

const tailwind = classNames => {
const obj = {};

	for (const className of classNames.split(' ')) {
-          if (styles[className]) {
		Object.assign(obj, styles[className]);
-           } else {
-                 console.warn(`Unsupported Tailwind class: "${className}"`);
-          }
	}

	return obj;
};

๐Ÿ˜„ I know it's a small package and maybe I'm exaggerating a bit. We will have to do a few benchmarks!

Font Weight probleme with some props

Hello,
font Weight semibold/thin/hairline don't seem to work, it render exactly the same. the doc don't mention any exception so they must be all supported, no ?

tested on Android.

also any ETA whene box shadow will be supported ?

Typed classnames for autocompletion

I like this API the most from the available Tailwind / RN projects but it's a bit sad to lose the ability for auto-completion.

What about going from this:

tailwind('bg-blue-200 px-3 py-1 rounded-full')

to something like this:

tailwind('bg-blue-200', 'px-3', 'py-1', 'rounded-full')

Using Plugins

Hello, first off great work on getting this on RN.

I wanted to ask if plugins are considered when customizing using npx create-tailwind-rn?
The reason I ask is because we are using a gradient plugin and noticed that the gradient utility classes aren't generated in the style.json file

Also last note. I noticed that anything set in the extend of tailwind config doesn't get pulled into the styles.json file

[Not an issue] Atom users - Get intellisense for tailwind-rn

I love tailwind-rn, but I don't love not having autocomplete. The utility classes with Tailwind are stellar and go hand-in-hand with Intellisense.

I opened a PR [here] to add it in to the atom-tailwindcss plugin.

One issue with it I see is that it will give you suggestions for all of Tailwind's classes, which will be confusing since tailwind-rn doesn't support all of them.

Length values under 1

Values like m-0.5, h-0.5, etc. don't work, although they are supported in Tailwind.

Font Weight with custom font

On Android, not all phones come with the Roboto font, so there's a need to install the Roboto font with several weights.
eg: Roboto thin, Roboto bold

The font needs to be referenced in the fontFamilly, eg

{
  text: {  fontFamily: 'Roboto Medium'},
  boldText: {fontFamily: 'Roboto Bold'}
}

I don't think there's a way to have a generic Text component eg

function Txt({children}) {
  return <Text style={Platform.select({android: {fontFamily: 'Roboto'})}>{children}</Text>
}

and then use tailwindcss weight:

function App() {
  return <Txt style={tw('font-bold')}>Hello World</Txt>
}

As the weight needs to be referenced in the fontFamily directly

style={tailwind()} vs className

Is there a reason why you chose to do this implementation vs className?

<Text style={tailwind('text-white p-4')}>Hi</Text

vs

<Text className="text-white p-4">Hi</Text

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.