JavaScript Post Tag - TechOpt.io https://www.techopt.io/tag/javascript Programming, servers, Linux, Windows, macOS & more Wed, 18 Jun 2025 14:23:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://www.techopt.io/wp-content/uploads/2024/07/cropped-logo-1-32x32.png JavaScript Post Tag - TechOpt.io https://www.techopt.io/tag/javascript 32 32 React Conditional Rendering: Logical AND vs Ternary Operator https://www.techopt.io/programming/react-conditional-rendering-logical-and-vs-ternary-operator https://www.techopt.io/programming/react-conditional-rendering-logical-and-vs-ternary-operator#respond Tue, 01 Apr 2025 22:30:57 +0000 https://www.techopt.io/?p=877 After building countless React and React Native components, I’ve run into one too many frustrating bugs caused by the logical AND (&&) operator used for conditional rendering in JSX. These issues are often subtle and hard to track down, so I’ve made it a rule: I don’t use logical AND for conditional rendering in JSX […]

The post React Conditional Rendering: Logical AND vs Ternary Operator appeared first on TechOpt.

]]>
After building countless React and React Native components, I’ve run into one too many frustrating bugs caused by the logical AND (&&) operator used for conditional rendering in JSX. These issues are often subtle and hard to track down, so I’ve made it a rule: I don’t use logical AND for conditional rendering in JSX anymore. Instead, I stick with the ternary (conditional) operator (in other words, shorthand “if” statement). It’s safer, clearer, and avoids nasty surprises.

The Problem with Logical AND for Conditional Rendering

Here’s a typical use case with logical AND:

{user.age && <Text>{`Age: ${user.age}`}</Text>}

You might expect this to only render the Text element if user.age is defined, or above 0 (since 0 is a falsy value in JavaScript).

But consider what happens if user.age is 0 (a valid, real-world age). We don’t want the <Text> element to get rendered in this case, and it doesn’t.

However, it creates a pretty unwanted side effect:

  • 0 && <Text>...</Text> evaluates to 0.
  • React will render the value 0 directly, essentially interpreting it as text instead of a boolean value!
    • In React Native, this is even worse: it will actually crash the entire application with an error about trying to render text outside of a <Text> component!

Example:

const user = { age: 0 };

return (
  <View>
    {user.age && <Text>{`Age: ${user.age}`}</Text>}
  </View>
);

What renders: Just 0. Not the <Text> element.

This happens because && doesn’t enforce a boolean context; it returns the first falsy value or the last truthy value. That means non-boolean values like 0 or "" can sneak through and show up unexpectedly. This can also crash your entire application in the case of React Native!

A Better Alternative: The Ternary Operator (Shorthand “if” Statements)

Instead, I use the ternary (conditional) operator, which makes the intent clearer and avoids rendering unwanted values:

{user.age ? <Text>{`Age: ${user.age}`}</Text> : null}

This guarantees that only a JSX element or null will be rendered; no accidental numbers or strings appearing in your layout.

Improved Example:

const user = { age: 0 };

return (
  <View>
    {user.age ? <Text>{`Age: ${user.age}`}</Text> : null}
  </View>
);

What renders: Nothing if age is undefined, null or 0, and the full Text block if it’s any other number.

Summary: Use the Ternary Operator for Conditional Rendering in React

While using && for conditional rendering may seem like a shortcut, it’s not always safe. This is especially true when your condition might evaluate to a falsy non-boolean like 0. From my experience, using the ternary operator leads to fewer bugs and a more predictable UI.

✅ Use:

condition ? <Component /> : null

🚫 Avoid:

condition && <Component />

When writing JSX in React or React Native, I choose clarity over cleverness. The ternary operator keeps my components clean and my debugging sessions short!

The post React Conditional Rendering: Logical AND vs Ternary Operator appeared first on TechOpt.

]]>
https://www.techopt.io/programming/react-conditional-rendering-logical-and-vs-ternary-operator/feed 0
App Center Alternatives for React Native Developers https://www.techopt.io/programming/app-center-alternatives-for-react-native-developers https://www.techopt.io/programming/app-center-alternatives-for-react-native-developers#respond Sun, 16 Mar 2025 02:47:39 +0000 https://www.techopt.io/?p=833 Microsoft’s decision to discontinue and sunset App Center has left many React Native developers searching for reliable alternatives. If you’ve been using App Center for building, testing, and distributing your apps, it’s time to explore new solutions. In this guide, we’ll break down the best App Center alternatives to help you keep your workflow efficient […]

The post App Center Alternatives for React Native Developers appeared first on TechOpt.

]]>
Microsoft’s decision to discontinue and sunset App Center has left many React Native developers searching for reliable alternatives. If you’ve been using App Center for building, testing, and distributing your apps, it’s time to explore new solutions. In this guide, we’ll break down the best App Center alternatives to help you keep your workflow efficient and uninterrupted.

Why Is App Center Being Discontinued?

App Center has been a go-to choice for mobile developers, providing CI/CD capabilities, automated testing, and distribution for iOS and Android apps. However, Microsoft has decided to sunset the platform, leaving teams to find replacement services that meet their needs. Therefore, selecting the right alternative is crucial. The key factors in choosing an alternative include build automation, real-device testing, seamless app distribution, and over-the-air (OTA) updates.

Best App Center Alternatives for React Native

1. EAS (Expo Application Services)

For teams using EAS, it provides an all-in-one solution for building, updating, and distributing React Native apps. As a result, it is one of the best alternatives to App Center, especially for projects already leveraging Expo.

  • Pros:
    • Seamless integration with Expo projects
    • No need for local machine setup
    • Cloud-based builds for iOS and Android
    • EAS Update serves as an alternative to CodePush, allowing for seamless OTA updates
  • Cons:
    • Primarily geared toward Expo-managed projects
    • Limited flexibility for bare React Native apps

2. Hot Updater (Self-Hosted CodePush Alternative)

If you relied on App Center for CodePush, a crucial feature for deploying over-the-air updates, you need a replacement. Fortunately, one of the best open-source alternatives is Hot Updater. This is my personal favourite CodePush replacement. It provides similar functionality while allowing you to self-host your own OTA update solution.

  • Pros:
    • Self-hosted, offering full control over updates
    • Supports both iOS and Android
    • Intuitive web console for managing versions
    • Plugin support for various storage providers (AWS S3, Supabase, etc.)
  • Cons:
    • Requires infrastructure setup and maintenance
    • Needs DevOps expertise for proper implementation

3. Bitrise

Bitrise is one of the most popular CI/CD platforms for mobile development. It offers cloud-based automation, supports React Native out of the box, and provides a flexible pipeline system for building, testing, and deploying apps. Consequently, many teams transitioning from App Center have found it to be a reliable alternative.

  • Pros:
    • Pre-configured workflows for React Native
    • Easy integration with GitHub, GitLab, and Bitbucket
    • Supports both iOS and Android
  • Cons:
    • Limited free-tier resources
    • Learning curve for advanced workflow customization

4. Codemagic

Codemagic is another excellent CI/CD tool that specializes in mobile development. It supports React Native projects and simplifies the build and deployment process with minimal configuration. Additionally, its user-friendly approach makes it a strong choice for teams looking for a quick transition.

  • Pros:
  • Cons:
    • Can get expensive for teams with heavy usage
    • Limited concurrent builds on the free plan

5. Firebase App Distribution

If your primary need is distributing pre-release versions of your app, Firebase App Distribution is a great alternative to App Center’s distribution feature. Moreover, it integrates well with other Firebase tools, making it an appealing choice for teams already using Firebase.

  • Pros:
    • Easy tester management
    • Integrates with Firebase Crashlytics for monitoring
    • Works for both iOS and Android
  • Cons:
    • No built-in CI/CD
    • Requires additional tools for automated builds

Choosing the Right App Center Alternative for Your React Native Project

The best App Center alternative depends on your specific needs:

As App Center sunsets, transitioning to a new platform early will help ensure a smooth workflow. Consequently, by selecting the right alternative, you can continue to build, test, distribute, and update your React Native apps with minimal disruption.

The post App Center Alternatives for React Native Developers appeared first on TechOpt.

]]>
https://www.techopt.io/programming/app-center-alternatives-for-react-native-developers/feed 0
Share Code Between React and React Native Projects https://www.techopt.io/programming/share-code-between-react-and-react-native-projects https://www.techopt.io/programming/share-code-between-react-and-react-native-projects#respond Fri, 27 Dec 2024 16:43:50 +0000 http://localhost:8080/?p=96 Sharing code between React and React Native projects improves development efficiency and ensures consistency. While UI code cannot always be shared (unless using react-native-web), you can reuse a lot of logic, such as context management, Redux stores, and utility functions. This approach helps reduce redundant work and streamlines project maintenance. Let’s dive into three methods […]

The post Share Code Between React and React Native Projects appeared first on TechOpt.

]]>
Sharing code between React and React Native projects improves development efficiency and ensures consistency. While UI code cannot always be shared (unless using react-native-web), you can reuse a lot of logic, such as context management, Redux stores, and utility functions. This approach helps reduce redundant work and streamlines project maintenance. Let’s dive into three methods to share code between React and React Native projects.

Why Share Code Between React and React Native?

React and React Native share the same core library, making it possible to reuse logic like hooks, contexts, and state management. By sharing code, you reduce development time and avoid duplicating functionality. This is especially helpful for projects that have both a web app and a mobile app with overlapping features.

However, sharing presentation components remains a challenge due to platform differences. Instead, focus on sharing non-UI elements like business logic, data processing, and utility functions.

Methods to Share Code Between React and React Native

1. Using a Monorepo

A monorepo centralizes multiple projects, such as your React app, React Native app, and shared logic, into a single repository. This structure simplifies managing shared code.

Advantages:

  • Centralized control over shared logic.
  • Simplified versioning with everything in one place.
  • Dependency management becomes easier using tools like Yarn Workspaces or Lerna.

How It Works:

  • Organize your repository into separate folders for the React app, React Native app, and shared code.
  • Link the shared code using a package manager like Yarn.
  • Import shared modules in your apps directly as local dependencies.

2. Using NPM Packages

Publishing shared logic as NPM packages provides a modular and flexible approach. These packages can either be hosted publicly on npmjs or in a private repository.

Why This Method Works Well:

  • Shared logic stays modular and independent.
  • Updating shared logic becomes seamless by bumping the package version in dependent projects.
  • Packages can easily be reused in other projects, even outside the React ecosystem.

How to Set It Up:

  1. Create a separate repository for shared logic.
  2. Develop your code and package it with tools like Rollup or Webpack if needed.
  3. Publish the package to npmjs or a private NPM registry.
  4. Install the package in both React and React Native projects.

Example:

// Inside shared-package.js
export function calculateDiscount(price, discount) {
  return price - price * (discount / 100);
}

// React App
import { calculateDiscount } from "my-shared-package";

// React Native App
import { calculateDiscount } from "my-shared-package";

This is personally one of my top methods for code sharing as I find it makes sharing complex code between React and React Native super clean and easy.

3. Good Old Copy and Paste

For small, one-off functions that are unlikely to change, copy-pasting offers a simple and fast solution. Although this method lacks scalability, it can work for minor use cases.

When to Use This Method:

  • The code is minimal and unlikely to evolve.
  • You need a quick solution for prototyping or experimentation.

Drawbacks:

  • Maintenance becomes challenging if changes are needed later.
  • Inconsistencies may arise if similar logic exists across multiple projects.

Example:

// Copied and pasted in both projects
function formatCurrency(amount) {
  return `$${amount.toFixed(2)}`;
}

Remarks

  • Choose your method based on the complexity of shared logic and project requirements.
  • NPM packages strike a good balance between flexibility and maintainability.
  • Monorepos suit tightly coupled projects but may increase setup complexity.
  • Minimize reliance on copy-pasting to avoid long-term maintenance issues.

By adopting these strategies, you can efficiently share code between React and React Native projects, reducing duplication and creating a cohesive development workflow.

The post Share Code Between React and React Native Projects appeared first on TechOpt.

]]>
https://www.techopt.io/programming/share-code-between-react-and-react-native-projects/feed 0
Handle Edge-to-Edge in React Native Android 15 (API 35) https://www.techopt.io/programming/handling-edge-to-edge-react-native-android-15 https://www.techopt.io/programming/handling-edge-to-edge-react-native-android-15#respond Thu, 19 Dec 2024 18:54:00 +0000 https://www.techopt.io/?p=526 With the release of Android 15 (API 35) and React Native 0.76, edge-to-edge layouts have become the default for modern Android apps. This change emphasizes the importance of handling safe area insets properly. If you’ve relied on React Native’s SafeAreaView, you’ve likely discovered that it doesn’t work on Android, as it was only designed with […]

The post Handle Edge-to-Edge in React Native Android 15 (API 35) appeared first on TechOpt.

]]>
With the release of Android 15 (API 35) and React Native 0.76, edge-to-edge layouts have become the default for modern Android apps. This change emphasizes the importance of handling safe area insets properly. If you’ve relied on React Native’s SafeAreaView, you’ve likely discovered that it doesn’t work on Android, as it was only designed with iOS’s notch in mind. Thankfully, the react-native-safe-area-context library offers a cross-platform solution that supports both Android and iOS.

In this article, we’ll walk you through the steps to replace SafeAreaView with View and utilize react-native-safe-area-context to ensure your layouts adapt to safe area insets correctly on Android.

Steps to Adapting Layout for Edge-to-Edge in React Native Android 15 (API 35)

1. Install the react-native-safe-area-context Library

If you haven’t already, add the library to your project using either npm or Yarn:

npm install react-native-safe-area-context

or

yarn add react-native-safe-area-context

2. Wrap your App with SafeAreaProvider

Add the SafeAreaProvider component to the root of your app and provide initialWindowMetrics to improve performance and avoid layout jumps on startup.

You can retrieve initialWindowMetrics from react-native-safe-area-context.

import React from 'react';
import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context';
import MyApp from './MyApp';

const App = () => (
  <SafeAreaProvider initialMetrics={initialWindowMetrics}>
    <MyApp />
  </SafeAreaProvider>
);

export default App;

3. Use Safe Area Insets Padding on Outer Views to Push Content out of Screen Edge

You can get child content to push into the safe area away from the screen edges by using padding on the outermost view. You should use useSafeAreaInsets for functional components, and withSafeAreaInsets for class components.

Examples

Functional Component

Here’s how to use the useSafeAreaInsets hook in a functional component:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const MyFunctionalComponent: React.FC = () => {
  const insets = useSafeAreaInsets();

  return (
    <View
      style={{
        ...styles.container,
        paddingTop: insets.top,
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
      }}
    >
      <Text>Hello, world!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

export default MyFunctionalComponent;
Class Component

Here’s how to use the withSafeAreaInsets higher-order component (HOC) in a class component:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { withSafeAreaInsets, SafeAreaInsetsContext } from 'react-native-safe-area-context';

interface Props {
  insets: SafeAreaInsetsContext;
}

class MyClassComponent extends React.Component<Props> {
  render() {
    const { insets } = this.props;

    return (
      <View
        style={{
          ...styles.container,
          paddingTop: insets?.top,
          paddingBottom: insets?.bottom,
          paddingLeft: insets?.left,
          paddingRight: insets?.right,
        }}
      >
        <Text>Hello, world!</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

export default withSafeAreaInsets(MyClassComponent);

That’s it! You can also decide which sides (top, bottom, left and right) you want to apply padding to based on the design of your screen. If you’re not sure, applying it to all sides and seeing how the screen looks is best.

Remarks

  • While react-native-safe-area-context exports a SafeAreaView component, our experience indicates that it can also lead to screen jumping issues, especially on iOS. Therefore, it’s still better to use the useSafeAreaInsets hook for functional components or the withSafeAreaInsets HOC for class components.
  • Passing initialWindowMetrics to SafeAreaProvider ensures accurate safe area insets on app startup, preventing layout jumps caused by delayed inset calculations.
  • For testing, you’ll want to use an Android emulator or phone that supports edge-to-edge and is running at least Android 15 (API 35), such as the Google Pixel 8.
  • If you were previously using SafeAreaView from react-native for iOS, you should remove all instances of SafeAreaView from your code. You can cross-reference our iOS guide here.

The post Handle Edge-to-Edge in React Native Android 15 (API 35) appeared first on TechOpt.

]]>
https://www.techopt.io/programming/handling-edge-to-edge-react-native-android-15/feed 0
Fix Screen Jumping Using SafeAreaView in React Native https://www.techopt.io/programming/fix-screen-jumping-safeareaview-react-native https://www.techopt.io/programming/fix-screen-jumping-safeareaview-react-native#respond Sun, 15 Dec 2024 00:10:03 +0000 https://www.techopt.io/?p=515 Screen jumping or flickering on mount is a common frustration when using SafeAreaView in iOS with React Native, specifically on devices with a notch or Dynamic Island. As these features are becoming increasingly common and now represent the majority of devices sold, addressing this issue is critical to ensure a smooth user experience. This problem, […]

The post Fix Screen Jumping Using SafeAreaView in React Native appeared first on TechOpt.

]]>
Screen jumping or flickering on mount is a common frustration when using SafeAreaView in iOS with React Native, specifically on devices with a notch or Dynamic Island. As these features are becoming increasingly common and now represent the majority of devices sold, addressing this issue is critical to ensure a smooth user experience. This problem, often referred to as “jumping SafeAreaView,” can interrupt the smooth user experience your app should deliver.

Thankfully, there’s a straightforward solution: replace SafeAreaView from the react-native library with View and leverage the react-native-safe-area-context library to handle safe area insets in a more optimized way.

In this article, we will guide you on how to implement this fix using TypeScript or JavaScript for both functional and class components.

Why Does Jumping with SafeAreaView Occur?

The screen jumping issue with SafeAreaView happens because of its initial rendering behavior on iOS. It’s unable to consistently calculate safe area insets before the content mounts, causing a noticeable flicker.

The react-native-safe-area-context library optimizes this process under the hood, ensuring a smoother rendering experience regardless of the device.

Steps to Fixing Screen Jumping when using SafeAreaView

1. Install the react-native-safe-area-context Library

If you haven’t already, add the library to your project using either npm or Yarn:

npm install react-native-safe-area-context

or

yarn add react-native-safe-area-context

2. Wrap your App in SafeAreaProvider

Add the SafeAreaProvider component to the root of your app and provide initialWindowMetrics to improve performance and avoid layout jumps on startup.

You can retrieve initialWindowMetrics from react-native-safe-area-context.

import React from 'react';
import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context';
import MyApp from './MyApp';

const App = () => (
  <SafeAreaProvider initialMetrics={initialWindowMetrics}>
    <MyApp />
  </SafeAreaProvider>
);

export default App;

3. Replace Instances of SafeAreaView with Padding Using Safe Area Insets

You should replace all instances of SafeAreaView throughout your application with insets using useSafeAreaInsets for functional components, or withSafeAreaInsets for class components.

Examples

Functional Component

Here’s how to use the useSafeAreaInsets hook in a functional component:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const MyFunctionalComponent: React.FC = () => {
  const insets = useSafeAreaInsets();

  return (
    <View
      style={{
        ...styles.container,
        paddingTop: insets.top,
        paddingBottom: insets.bottom,
        paddingLeft: insets.left,
        paddingRight: insets.right,
      }}
    >
      <Text>Hello, world!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

export default MyFunctionalComponent;
Class Component

Here’s how to use the withSafeAreaInsets higher-order component (HOC) in a class component:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { withSafeAreaInsets, SafeAreaInsetsContext } from 'react-native-safe-area-context';

interface Props {
  insets: SafeAreaInsetsContext;
}

class MyClassComponent extends React.Component<Props> {
  render() {
    const { insets } = this.props;

    return (
      <View
        style={{
          ...styles.container,
          paddingTop: insets?.top,
          paddingBottom: insets?.bottom,
          paddingLeft: insets?.left,
          paddingRight: insets?.right,
        }}
      >
        <Text>Hello, world!</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

export default withSafeAreaInsets(MyClassComponent);

That’s it! You can also decide which sides (top, bottom, left and right) you want to apply padding to based on the design of your screen. If you’re not sure, applying it to all sides and seeing how the screen looks is best.

Remarks

  • While react-native-safe-area-context exports a SafeAreaView component, our experience indicates that it can also lead to screen jumping issues. For a robust and future-proof solution, use the useSafeAreaInsets hook for functional components or the withSafeAreaInsets HOC for class components.
  • Passing initialWindowMetrics to SafeAreaProvider ensures accurate safe area insets on app startup, preventing layout jumps caused by delayed inset calculations.
  • SafeAreaView is likely to be deprecated soon. With the introduction of edge-to-edge layouts on Android 15 (API 35) and React Native 0.76, the community is shifting toward react-native-safe-area-context for cross-platform consistency.
  • react-native-safe-area-context natively supports safe area insets on both iOS and Android, making it the ideal choice compared to SafeAreaView from react-native.

The post Fix Screen Jumping Using SafeAreaView in React Native appeared first on TechOpt.

]]>
https://www.techopt.io/programming/fix-screen-jumping-safeareaview-react-native/feed 0
Add Tailwind CSS to an Existing Next.js Project https://www.techopt.io/programming/add-tailwind-css-to-an-existing-next-js-project https://www.techopt.io/programming/add-tailwind-css-to-an-existing-next-js-project#respond Sat, 03 Aug 2024 20:00:26 +0000 http://localhost:8080/?p=88 If you have an existing Next.js project using plain CSS or CSS modules, you may decide to add Tailwind CSS at some point. During recent years, Tailwind CSS has become increasingly popular for its simplicity and ease-of-use. The good news is Tailwind can inter-op with plain CSS and CSS modules quite easily without affecting your […]

The post Add Tailwind CSS to an Existing Next.js Project appeared first on TechOpt.

]]>
If you have an existing Next.js project using plain CSS or CSS modules, you may decide to add Tailwind CSS at some point. During recent years, Tailwind CSS has become increasingly popular for its simplicity and ease-of-use.

The good news is Tailwind can inter-op with plain CSS and CSS modules quite easily without affecting your existing work. At the same time, this makes it easy to adopt gradually, even in big projects with lots of custom styling already.

Adding Tailwind CSS to the Project

To add Tailwind to an existing Next.js project, you can follow these steps.

1. Install Tailwind Package

Install the tailwindcss package with yarn or npm by running

yarn add tailwindcss

2. Add (or Update) postcss.config.js

If you don’t already have a postcss.config.js file in your project’s root, create one with the following contents:

// postcss.config.js

module.exports = {
  "plugins": [
    ["tailwindcss", {}]
  ]
}

If you do already have a postcss.config.js file, just add the tailwindcss plugin to the list of plugins like above.

3. Create Tailwind Config File

Create a tailwind.config.js or tailwind.config.ts file in your project’s root with the following contents:

// tailwind.config.ts
// This example is using TypeScript instead of plain JavaScript

import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
 
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

export default config;

Or if you prefer plain JavaScript:

// tailwind.config.js
// This is for JavaScript

module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
 
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

4. Add Tailwind Directives to globals.css File

Your Next.js project should already have a globals.css file or equivalent. Add the Tailwind directives at the top of it:

/* globals.css */

@tailwind base;
@tailwind components;
@tailwind utilities;

/* rest of css code */

5. Test it Out!

Start your dev server with yarn run dev and test out some Tailwind in your React code. You can do something like the following:

// index.tsx

export default function Home() {
  return (
    <div className="text-green-400 font-bold underline">
      Hello world!
    </div>
  )
}

You should see some green text, underlined in bold!

Inter-oping Tailwind CSS with Existing CSS & CSS Modules

If you’re already using regular CSS or CSS modules in your project, thankfully you can use Tailwind CSS class names with existing class names.

CSS modules just output a class name, so we can use our CSS module classes in addition to the Tailwind classes.

Using Tailwind Classes with CSS Modules

CSS modules just outputs unique class names. Because of this, we can use existing CSS module classes with Tailwind CSS by using template literals:

// index.tsx
import styles from '@/styles/pages/Home.module.css'

export default function Home() {
  return (
    <div className={`${styles.styled_text} text-green-400 font-bold underline`}>
      Hello world!
    </div>
  )
}

This will combine our rules from our existing CSS modules with the Tailwind classes we’ve added.

Optional: Disabling Opinionated Default Tailwind Styling Decisions

When you install Tailwind, it makes some opinionated default styling decisions on some elements to normalize the look across browsers. This is fine for new projects, but if you’ve been using CSS modules up until this point, it may mess up some of your existing styling.

To disable this behaviour, you can add the option preflight: false under the corePlugins option in your Tailwind config file, like so:

// tailwind.config.ts
// This example is using TypeScript instead of plain JavaScript

import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
  corePlugins: {
    preflight: false
  }
}

export default config;

This will disable the default normalization styling decisions Tailwind makes, such as making all headers normal-sized text and not bold.

Remarks

  • This guide was adapted from the official Tailwind guide to go more in depth, and assumes the use of newer standards such as TypeScript.
  • Some guides mention installing postcss and autoprefixer packages in addition to Tailwind, but this isn’t necessary since Next.js comes with PostCSS support built-in.

The post Add Tailwind CSS to an Existing Next.js Project appeared first on TechOpt.

]]>
https://www.techopt.io/programming/add-tailwind-css-to-an-existing-next-js-project/feed 0