Movatterモバイル変換


[0]ホーム

URL:


TW Elements Next integration

This article shows you how to integrate Next application with TW Elements. Free download, open source license.


Prerequisites

Before starting the project make sure to install the following utilities:

  • Node LTS (18.x.x or higher recommended)
  • Code editor. We recommendVSCode

Creating a new Next application

Let's create a fresh Next application so that we can go through all the steps together.

Step 1

Create new project.

Note: Options used while creating the app: Typescript -Yes, ESLint -Yes, `src/` directory -Yes, App Router -both examples included in this tutorial.

If you encounter theRequest is not defined error, consider updating yourNode.js version to at leastv18.0.0 or higher. Alternatively, you can useNext.js v13.0.0 or a more recent version to address this issue.

                npx create-next-app@latest    cd my-project

Step 2

Run the development server.

                npm run dev

Installing and configuring Tailwind CSS and TW Elements

Step 1

Install Tailwind CSS.

                npm install -D tailwindcss postcss autoprefixer    npx tailwindcss init -p

File structure

If you have created a new next app, depending on the chosen options, your file structure could look like this:

        // with App Router        my-project/        ├── node_modules/        ├── public/        ├── src/                │   ├── pages/ - needs to be created        │   ├── app/        │   │   ├── favicon.ico        │   │   ├── globals.css        │   │   ├── layout.tsx        │   │   └── page.tsx        │   ├── index.css        │   ├── ...        │   └── index.js        ├── package-lock.json        ├── package.json        ├── postcss.config.js        ├── next.config.js        ├── tsconfig.config.js        ├── ...        └── tailwind.config.js        // without App Router        my-project/        ├── node_modules/        ├── public/        ├── src/                │   ├── pages/        │   ├──── app/        │   │     ├── _app.tsx        │   │     ├── _document.tsx        │   │     └── index.tsx        │   └── styles/        │         └── globals.css        ├── package-lock.json        ├── package.json        ├── postcss.config.js        ├── next.config.js        ├── tsconfig.config.js        ├── ...        └── tailwind.config.js

Step 2

Add the paths to all of your template files in yourtailwind.config.js file.

                /** @type {import('tailwindcss').Config} */    module.exports = {      content: [        "./app/**/*.{js,ts,jsx,tsx}",        "./pages/**/*.{js,ts,jsx,tsx}",        "./components/**/*.{js,ts,jsx,tsx}",        "./node_modules/tw-elements/js/**/*.js",        // Or if using `src` directory:        "./src/**/*.{js,ts,jsx,tsx}",        "./node_modules/tw-elements/js/**/*.js"      ],      theme: {        extend: {},      },      darkMode: "class",      plugins: [require("tw-elements/plugin.cjs")]    }

Step 3

Add the@tailwind directives for each of Tailwind's layers to yourglobals.css. Additionally, delete the default font styles inlayout.tsx file.

                @import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,900&display=swap");    @tailwind base;        @layer base {      html {        @apply text-surface;        @apply bg-white;      }      html.dark {        @apply text-neutral-50;        @apply bg-body-dark;      }    }        @tailwind components;    @tailwind utilities;        p {      @apply leading-[1.6];    }

Step 4

Install TW Elements.

                npm install tw-elements

Step 5

Create standalone file with name of your component (for exampleMyComponent.tsx insrc/pages directory - create one if it doesn't exist) and add dynamic import TWE components which are you intend to use. Also include necessary functioninitTWE. InitializeinitTWE in a lifecycle method. Sincetw-elements needs to be usedclient side don't forget to add"use client" at the beginning of the file.

                "use client";    import { useEffect } from "react";        const MyComponent = () => {      useEffect(() => {        const init = async () => {          const { Tooltip, initTWE } = await import("tw-elements");          initTWE({ Tooltip });        };        init();      }, []);          return (        <div className="mt-16 flex justify-center">          <p className="text-lg">            Hover the link to see the            <a              href="#"              className="text-primary ps-1 transition duration-150 ease-in-out hover:text-primary-600 focus:text-primary-600 active:text-primary-700 dark:text-primary-400 dark:hover:text-primary-500 dark:focus:text-primary-500 dark:active:text-primary-600"              data-twe-toggle="tooltip"              title="Hi! I'm tooltip"            >              tooltip            </a>          </p>        </div>      );    };        export default MyComponent;

Step 6

Import the newly created component wrapping it intodynamic import withssr object set tofalse. You can do it either in./src/app/page.tsx or./src/pages/index.tsx.

                import dynamic from "next/dynamic";    const DynamicComponent = dynamic(() => import("../pages/MyComponent"), {      ssr: false,    });        const Home = () => {      return (        <>          <DynamicComponent />        </>      );    };        export default Home;

Step 7

This step enables the reloading of Tailwind CSS styles. Start the app and see if everything's fine. Awesome! You're all set to dive into using TW Elements for your Next project. Have fun!

                npm run dev

Initializing via JS

By default all components have autoinit which means they are initialized by data attributes. But if you want to make init by JavaScript - there is also possibility to do that.

Step 1

Import components which are you intend to use and initialize components in lifecycle hook.

                "use client";    import { useEffect } from "react";        const MyComponent = () => {      useEffect(() => {        const init = async () => {          const { Tooltip } = await import("tw-elements");              const myTooltip = new Tooltip(document.getElementById("my-tooltip"));        };        init();      }, []);          return (        <div className="mt-16 flex justify-center">          <p className="text-lg">            Hover the link to see the            <a              id="my-tooltip"              href="#"              className="text-primary ps-1 transition duration-150 ease-in-out hover:text-primary-600 focus:text-primary-600 active:text-primary-700 dark:text-primary-400 dark:hover:text-primary-500 dark:focus:text-primary-500 dark:active:text-primary-600"              title="Hi! I'm tooltip"            >              tooltip            </a>          </p>        </div>      );    };        export default MyComponent;

Troubleshooting

Problem overview:

Users might face difficulties with improper functioning of components in some frameworks for TW Elements. This is due to the fact that some of them aren't initializing properly.

Suggested solution:

Consider importingtw-elements package dynamically. By doing it, you can enhance the initialization process, potentially resolving any issues related to component functionality. Additionally, ensure that theinitTWE() method is called in the correct sequence and with the appropriate parameters, facilitating a smoother experience with TWE components.

Note: It should also solve errors likedocument is not defined or(Name of TWE Component) is not imported from "tw-elements". For the second issue, attempting to import components inES format could be an alternative solution.

ES import:

                      // next.config.js          module.exports = {            webpack: (config, { isServer }) => {              // For packages that provide different entry points, specify the one you want to use.              config.resolve.alias = {                ...config.resolve.alias,                "tw-elements":                  "tw-elements/dist/js/tw-elements.es.min.js",              };              return config;            },          };          // component.tsx          useEffect(() => {            import { Tooltip, initTWE } from "tw-elements";                        initTWE({ Tooltip };)          }, []);
                      useEffect(() => {            import { Tooltip, initTWE } from "tw-elements/dist/js/tw-elements.es.min.js";                        initTWE({ Tooltip };)          }, []);

ES Dynamic import:

                      useEffect(() => {            const init = async () => {              const { Tooltip, initTWE } = await import("tw-elements");              initTWE({ Tooltip });            };            init();          }, []);

Source TW Elements Team

Problem overview:

Users may encounter initialization issues with TWE components when navigating through applications with routing mechanisms. The default behavior of theinitTWE method includes checking if components are already initialized, which can lead to complications when components are unmounted and then remounted during routing.

Suggested solution:

Consider using usingautoReinits option ininitTWE method. By default it's value is set tofalse. By changing the value totrue, theinitTWE method won't check if components were already initialized.

                        initTWE({ Tooltip }, { allowReinits: true });

Source TW Elements Team


Related resources

Tutorials:

Integrations :

Design System (Figma):


[8]ページ先頭

©2009-2025 Movatter.jp