I’m writing a small app using React Native. Since I’m a fan of Tailwind for styling on the web, I wanted to use it for the app as well. The package tailwind-rn
is available, but requires the use of tailwind('...')
to apply styles, which doesn’t work with the intellisense plugin for VSCode.
Wouldn’t it be nice to both be able to use regular className
props and get intellisense working, all at the same time? Of course it would.
Using a small higher-order component (HOC), it’s doable:
import * as React from "react";
import tailwind from "tailwind-rn";
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || "Component";
}
export function withTailwind(Component) {
function ComponentWithTailwind({ className, style, ...rest }) {
const classes = className
? Array.isArray(className)
? className.flat().filter(Boolean).join(" ")
: className
: "";
return <Component style={[tailwind(classes), style && style]} {...rest} />;
}
ComponentWithTailwind.displayName = `withTailWind(${getDisplayName(
Component
)})`;
return ComponentWithTailwind;
}
By re-exporting the relevant components from react-native
, className
props are then available everywhere:
import * as RN from "react-native";
import { withTailwind } from "./withTailwind";
export const Text = withTailwind(RN.Text);
export const View = withTailwind(RN.View);
// ... etc
The HOC allows both for string and array props. Autocomplete works for both. 🎉
import { View, Text } from "./Base";
function Test() {
return (
<View className="bg-white">
<Text className={["text-black"]}>Success!</Text>
</View>
);
}