Search code examples
react-nativeanimationtailwind-cssclassname

How to use tailwind animation in react-native with classname?


i try to animate some component like view or button by using Tailwind in my expo react-native project by no success in addition into website doc i noticed that it support animation and transition Robust Animations - Full support for Tailwind's animation classes and custom keyframe animations via react-native-reanimated

🔄 Transitions - Smooth transitions between style states, including dark mode changes and dynamic updates
https://www.nativewind.dev/

 <Button title='press' className="transition ease-in-out delay-150 bg-blue-500 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300 ..."/>

Solution

    1. make sure you installed the needed the needed dependencies:

      npm install nativewind react-native-reanimated

      if you're using expo:

      npm install --save-dev babel-plugin-tailwindcss-react-native

    2. config your babel.config.js, your babel.config.js should look like this:

    module.exports = function (api) {
      api.cache(true);
      return {
        presets: [
          ["babel-preset-expo", { jsxImportSource: "nativewind" }],
          "nativewind/babel",
        ],
        plugins: ["react-native-reanimated/plugin",'babel-plugin-dotenv'],
      };
    };

    1. now you also need to config tailwind.config.js for the project, if you dont have it then:

      npx tailwindcss init

      then change the content to this:

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./app/**/*.{js,jsx,ts,tsx}",
        "./components/**/*.{js,jsx,ts,tsx}",
      ],
    ...
    }

    1. import this in your root _layout : import 'react-native-reanimated';

    2. now after making sure you've configured everything right this is an example of how you define your own Animations in the tailwind.config.js:

    module.exports = {
      theme: {
        extend: {
          animation: {
            'fade-in': 'fadeIn 1s ease-in-out',
          },
          keyframes: {
            fadeIn: {
              '0%': { opacity: 0 },
              '100%': { opacity: 1 },
            },
          },
        },
      },
    };

    then use it like this:

    <View className="animate-fade-in">
      <Text>Hello, world!</Text>
    </View>