Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NativeWind will transform className into style as an array, can it be one single style object

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'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;

  1. mergeStyles function: This function checks if the styles prop 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.
  2. mergedStyle variable: This variable holds the merged style object obtained from the mergeStyles function.
  3. Passing mergedStyle to tw.style: The mergedStyle is then passed to tw.style to 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading