i use both NativeWind and twrnc in my project.
suppose i have a component looks like this.
import tw from "twrnc";
...
const Test=(props)=>
{
console.log(props);
return <View style={tw.style(`border`,props.style)}>
<Text>hello</Text>
</View>
}
and when i try to use this component like this
<Test className="bg-red-400 text-red-400" />
it will print out the props like this:
style: [{backgroundColor: '#f87171'},{color: '#f87171'}]
the NativeWind transformed classname into style but as an array.
then tw.style will popup an error which says TypeError: str.trim is not a function (it is undefined)
is it possible to ask NativeWind not transform classname into style array, but a single style object?
for example, style: {backgroundColor: '#f87171', color: '#f87171'}
>Solution :
In your project, when using both NativeWind and twrnc, the transformation of class names into style arrays by NativeWind can lead to issues when those styles are passed to tw.style. To address this problem, you can manually merge the styles array into a single object before passing it to tw.style.
import React from 'react';
import { View, Text } from 'react-native';
import tw from 'twrnc';
import { StyleSheet } from 'react-native';
const mergeStyles = (styles) => {
if (Array.isArray(styles)) {
return styles.reduce((acc, style) => ({ ...acc, ...style }), {});
}
return styles;
};
const Test = (props) => {
const mergedStyle = mergeStyles(props.style);
return (
<View style={tw.style(`border`, mergedStyle)}>
<Text>hello</Text>
</View>
);
};
export default Test;
mergeStylesfunction: This function checks if thestylesprop is an array. If it is, it merges the array elements into a single object. If it’s already an object, it returns the object as is.mergedStylevariable: This variable holds the merged style object obtained from themergeStylesfunction.- Passing
mergedStyletotw.style: ThemergedStyleis then passed totw.styleto ensure it works correctly without causing any errors.
<Test className="bg-red-400 text-red-400" /> test this it will properly merged into a single object.
check this, it will work.