0

i installed tailwind-rn for my react native project i did the configuration and used this syntax provided in the console after installation

   import {useTailwind} from 'tailwind-rn';
   const MyComponent = () => {
     const tailwind = useTailwind();

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

but for me i have a class component so i did this

render() {
    const tailwind = useTailwind();
    return (
      <View style={tailwind("style classes...")}>
         ...
      <View/>
    );
}

and i got this error

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

i searched how to use tailwind-rn for a class component and i didn't find something usefull.

  • you cant use hooks inside class components – Ushan Fernando Jul 22 '22 at 16:08
  • @UshanFernando, so how to use tailwind in a class component ? That's the question – Hamza-Snoussi Jul 22 '22 at 17:40
  • as far as i know they dont provide any official support, what you are trying to use is a community driven package. if the dev of the package doesnt provide class component support then you cant do it – Ushan Fernando Jul 22 '22 at 18:06
  • Thank you for your reply, is there an official package for the use of tail wind in react native ? – Hamza-Snoussi Jul 22 '22 at 20:01
  • Does this answer your question? [Using recoil.js in react, in class component without using hooks](https://stackoverflow.com/questions/62860300/using-recoil-js-in-react-in-class-component-without-using-hooks) – Abe Jul 22 '22 at 23:26
  • https://github.com/vadimdemedes/tailwind-rn/issues/142#issuecomment-1035959468 you can use like this i guess. – Nazır Dogan Jul 23 '22 at 06:40

1 Answers1

1

While it's not formally exposed (directly at least) you can access the context and use it in a Class based component. This example assumes you only need 1 context, but you can use the pattern seen here if you need access multiple context providers.

import * as React from 'react';
import TailwindContext from 'tailwind-rn/dist/tailwind-context';

export class TailwindWithClassComponents extends React.Component {
  static contextType = TailwindContext;

  render() {
    const tailwind = this.context;

    return <Text style={tailwind('uppercase')}>Testing...</Text>;
  }
}
visormatt
  • 329
  • 2
  • 6