React Native has a pretty good place to be when it comes to styles. The built-in StyleSheet method allows you to easily decouple styles outside JSX.
Sticking with React Native is usually a good idea, but it’s not without its drawbacks. First, it can be difficult to maintain styles in some external locations to reuse them. Another problem is managing appropriate naming conventions throughout the code base. These issues can be addressed by using Tailwind in React Native.
Tailwind CSS completely changes the common approach to structuring CSS. As you learn good code practices, developers quickly learn the importance of separation of concerns and separating HTML and CSS between two files. Utilitarian CSS seems completely different.
While there has been some dissatisfaction in the developer community with utility-first CSS, it’s hard not to notice Tailwind CSS gaining in popularity. As a testament to its capabilities, Tailwind won The Most adopted technology award in The State of CSS 2020 survey.
So what’s all the fuss about?
Use the first method
In React Native, utility priority classes apply specific CSS attributes to an element through their class or style attributes. The old approach was to apply the style object to the inline of the element, or to reference the keys of the StyleSheet object and apply a custom name.
Utilitarian class methods allow you to simply add a class name to an element without having to write a custom style. Decisions have been made to implement color, typography, and structure, as well as to provide a meaningful name for each stylized element.
Tailwind gives you default values based on a solid design system, which results in consistency throughout the codebase. The learning curve may seem steep at first, but a developer proficient in this type of stylization is able to work faster and in a more uniform manner. In addition, when a team uses a carefully curated set of limited options, it’s easier to add a new developer and keep your style design approach consistent.
Finally, because StyleSheets are reused, the code base stops growing and is therefore easier to maintain.
Compare ways to stylize components
Using styled components is a good style design approach for many reasons. However, not knowing at first glance whether a component is React or dumb can really slow things down. Premature abstraction also occurs when we create components that will never be reused.
Consider the inline style
One drawback when it comes to mixing code with Tailwind classes is that our code can get wordy pretty quickly. In general, we avoid inline styles at all costs, as they have a negative impact on code readability and can hurt overall performance. There is some suggestion from the developer community that the StyleSheet method is more efficient than inline styles because it sends the entire object across the bridge at once. This is further clarified in the React Native source code.
Use Tailwind in React Native
While there are several Tailwind packs that work well with React Native, But I chose to use tailwind-react-native classnames over tailwind-rn. Tailwind-react-native classnames is based on classnames, which is a JavaScript tool, Used to improve Tailwind code on the Web, so developers using Tailwind CSS should be familiar with it.
Feel free to use different libraries, but for me, the tagged template function approach is more like. The styles passed to arrays in.NET are more visually appealing. [react-native-tailwindcss](https://github.com/TVke/react-native-tailwindcss). You can also choose to simply React Native components from [the React – Native – tailwind] (https://www.npmjs.com/package/react-native-tailwind) in the library to import the React Native component and pass the class to className Prop.
There are two ways to apply tailwind to elements using the tailwind-react-native-classnames library. The basic one is the template function using the ES6 tag, which simply wraps the class name in a backslash, like the View element below. The second approach, using the Classnames package, allows you to compose classes and handle more complex cases. Notice it in the Text element below.
import tw from 'tailwind-react-native-classnames';
const MyComponent = () => (
<View style={tw`bg-blue-100`}>
<Text style={tw.style('text-md', invalid && 'text-red-500')}>Hello</Text>
</View>
);
Copy the code
React Native specific class
We have two React Native classes that use platform-specific styles to safely use the tag template functionality.
tw`ios:pt-4 android:pt-2`;
Copy the code
Tailwind class name
If you look at the menu on the left side of Tailwind’s home page, you’ll see several sections. Only a few of these relate to React Native, but if you already know how to style components in React Native, you’ll quickly learn what you can use. The best part for you to read is.
- Layout: Handles issues such as size and location
- Flexbox: Use Flexbox to locate elements
- Spacer: Class of fillers and margins
- Dimensions: width and dimension classes
- Typography: Everything related to fonts, letter spacing, and text
- Background: classes such as background color, image, and background opacity.
- Border: radius, width, and color classes
There’s also the effects section, where you can find opacity, but it’s also possible to use classes. Tailwind -react-native-classnames are in shadow, which is in the box shadow part of this section.
I also found this cheat sheet very useful. You can check the correct code for element attributes when trying to specify values. For example, when you set the element width, you can use the name of the w-class and set the number W-40 to 160px.
Compare StyleSheet and Tailwind CSS
Now, let’s build a simple layout using two methods to compare Tailwind code with React Native code. For this example, I decided to create a ScrollView with cards. A selected variable is passed to the component, which determines the colors of the different backgrounds and title sets.
The entire code example for this article is located in the Git repository tailwind CssActNative. You can also run this example from Expo. First, we will use the StyleSheet method to build the above components.
const ListItem = ({ uri, selected = false, text="" }) => { return ( <View style={[styles2.container, { ...(! selected && { backgroundColor: '#FFFFFF'})}]}> <View style={styles2.logoBackground}> <Image style={styles2.logo} source={ uri } /> </View> <Text style={[styles2.text, { ...(!selected && { color: 'black'})}]}>{ text }</Text> <TouchableOpacity style={styles2.button}> <Text style={styles2.buttonText}>Details</Text> </TouchableOpacity> </View> ) }Copy the code
As you can see, three items are passed: the URI of the image, the text of the card title, and information about whether the component is selected. Depending on whether selected is true or false, additional styles are added, such as backgroundColor in the main view and color in the Text component.
StyleSheet is used to style this component.
const styles2 = StyleSheet.create({ container: { height: 256, width: 160, backgroundColor: 'rgba(59,130,246,1)', borderRadius: 12, padding: 15, margin: 5, alignItems: 'center', justifyContent: 'center', opacity: "#000", shadowOffset: {width: 0, height: 3,}, shadowRadius: 4.65, elevation: 6,}, logoBackground:{width: 112, height: 112, borderRadius: 55, backgroundColor: '#E4F0FE'}, logo: { width: 110, height: 110, borderRadius: 55 }, text: { color: 'white', fontSize: 18, fontWeight: 'bold', marginVertical: 10 }, button: { height: 40, width:'100%', backgroundColor: 'white', borderRadius: 16, alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: 'rgba(59,130,246,1)'}, buttonText: {color: 'rgba(59,130,246,1)', fontSize: 17, fontWeight: 'bold'}});Copy the code
Now we can build the same component using the Tailwind CSS method and the Tailwind – React-native -classnames library.
import React from 'react'; import { Text, View, TouchableOpacity, Image } from 'react-native'; import tw from 'tailwind-react-native-classnames'; export const ListItemTW = ({ uri, selected = false, text="" }) => ( <View style={tw.style( 'h-64 w-40 bg-blue-500 rounded-xl p-4 m-1 items-center justify-center shadow-lg', ! selected && 'bg-white' )}> <View style={tw`w-28 h-28 rounded-full bg-indigo-50`}> <Image style={tw`w-28 h-28 rounded-full`} source={ uri } /> </View> <Text style={tw.style( 'text-white text-lg font-bold my-4', ! selected && 'text-black' )}> { text } </Text> <TouchableOpacity style={ tw`h-10 w-full bg-white rounded-full items-center justify-center border border-blue-500` } > <Text style={tw`text-lg text-blue-500 font-bold`}> Details </Text> </TouchableOpacity> </View> )Copy the code
So, what’s the difference? Note that the Tailwind component has 36 lines, while the normal component that uses StyleSheet has 76 lines. The biggest drawback is that there are several lines of code. There are two or even more lines because the tw.style of Classname is used to connect the class to the conditionally added style.
There are advantages and disadvantages to using predefined styles. As mentioned earlier, the benefits are faster development time and easier maintenance. The biggest drawback is that if you use some unusual values, such as sizes or colors that are not included in standard values, you will have to customize your style. I think the easiest way to do this is to pass the style object to tw.style, which should make it easy to identify.
conclusion
Using Tailwind CSS in your project can unify the entire code base. In StyleSheet, instead of giving styles custom names, you can apply class names from a predefined list that is already familiar to many developers.
In addition, the speed of development should increase because it is easier to style components and evaluate which styles apply to particular elements. This approach has its drawbacks, such as making some components too verbose. I believe these problems can be solved by exporting some of the longer, reusable parts as styled components, or exporting them to external files, but it depends on how you determine the best approach for your project.
The postWhy you should use Tailwind CSS with React Nativeappeared first onLogRocket Blog.