The CSS styles for a React component in Rollup are not being incorporated into the server-side rendering document in NextJS

I recently created a small npm package that exports a single component. The component is styled using SCSS modules and bundled with Rollup. Everything appeared to be working well until I imported it into a NextJS project, where I noticed that the styles are not applied immediately to the SSR'd document from NextJS (although they eventually get applied, there is a brief moment where the component appears unstyled).

This is my first time developing an npm package and using Rollup, so I am struggling to resolve this issue. Should I avoid bundling the CSS into the .js files and recommend users to import the css files themselves? Although I wanted to simplify the process for users by avoiding this additional step. Another potential solution could be using CSS-in-JS, but I prefer not to add another dependency if possible.

Any guidance or tips would be greatly appreciated!

Here is a snippet of my Rollup configuration:

const config = [
  {
    input: "src/lib/index.ts",
    output: [
      {
        file: pkg.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: pkg.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      url(),
      svgr(),
      typescript({ tsconfig: "./tsconfig.json", rootDir: "src/lib" }),
      postcss({
        modules: true,
      }),
      terser(),
      bundleSize(),
      visualizer(),
    ],
  },
  {
    input: "dist/esm/types/index.d.ts",
    output: [{ file: "dist/index.d.ts", format: "esm" }],
    plugins: [
      dts(),
      del({ hook: "buildEnd", targets: ["dist/cjs/types", "dist/esm/types"] }),
    ],
  },
];

In case it's relevant, here is a portion of my tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "jsx": "react",
    "module": "ESNext",
    "declaration": true,
    "declarationDir": "types",
    "sourceMap": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "removeComments": true,
    "plugins": [{ "name": "typescript-plugin-css-modules" }]
  },
  "include": ["src/lib/customModules.d.ts", "src/**/*"]
}

Answer №1

Next.js, with its unique dual compilation process for server and client-side code, presents a challenge when it comes to injecting CSS.

To work around this limitation, the recommended solution is to create a separate CSS file for your library and then incorporate it into your Next.js application.

You can import the built CSS file in the layout file (src/app/layout.jsx or tsx) of your Next.js application, like so:

import 'my-component/index.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

For more information on this topic, please refer to: How to use styled-components with rollup and next.js - css not imported

Answer №2

When working with CSS-in-JS libraries or specific styling techniques in Next.js for React components, you may run into challenges with Server-Side Rendering (SSR) where the styles added by components are not present in the initial HTML document. Below are some possible causes and remedies:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to update the URL dynamically in a Next.js application without relying on the <Link> component?

I'm looking for a way to dynamically change the URL on a page without using <Link>. Specifically, I want to switch to a different URL when a variable changes from false to true, regardless of user interaction. Currently, I'm achieving this ...

How can I implement server-side rendering for SVG graphics with React?

Currently working on a project utilizing both Highcharts and React where server side rendering for the SVG generated is crucial. Any recommendations on how to achieve this in order to obtain a static rendered page with images in png/jpg format? The browser ...

What is the best way to have NextJS add styles to the head in a production environment?

Typically, NextJS will include <style> tags directly in the head of your HTML document during development (potentially utilizing the style-loader internally). However, when running in production mode, NextJS will extract CSS chunks and serve them as ...

A step-by-step guide on setting up flow types for @material-ui/core version 4

Is there a way to install flow types for material-ui/core version 4.x.x? It seems like the last update was for version 1.x.x here. The documentation on this topic is quite limited here. I'm unsure if there is still support for this, especially since t ...

Is it necessary to write Higher Order Component in React as a function?

As I dive into learning React, the concept of Higher Order Components (HOCs) becomes clearer. Take for instance the following example extracted from React's official documentation: function withSubscription(WrappedComponent, selectData) { // ...a ...

React Native - state hook refreshes and causes the component to re-render, yet no changes are visible

Here is the code snippet: export default () => { const [albums, setAlbums] = useState([]); useEffect(() => { MediaLibrary.getAlbumsAsync().then((tmpAlbums) => { setAlbums(tmpAlbums); }); }, []); return ( ...

Guide on capturing user permissions to determine the inactivity delay

Within this NextJS application, there is a file named permissions.tsx, structured as follows: // @ts-nocheck import { useState, useEffect } from 'react' import { useSession } from 'next-auth/client' function usePermissions() { const [p ...

What's up with the Twitter Bootstrap parameters?

As a beginner in the world of HTML5 and Twitter Bootstrap, I have been exploring some pre-built examples and now have a few questions... Consider this code snippet from the Fluid Layout Example: <div class="navbar navbar-fixed-top"> <div class ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

What is the best way to create a dropdown menu that smoothly slides in from the bottom of the screen?

Is it possible to create dropdown menus in the navigation bar that slide in from the bottom with a smooth transition effect, similar to this example: Although I am working on building my own template, so my code may differ from the original theme. Here is ...

What is the best way to display a hand symbol (cursor pointer) when the mouse hovers over a date field in Material UI?

Can someone help me figure out how to display a cursor pointer when hovering over a TextField with the type 'date'? Below is the sandbox link for reference. Thank you. Sandbox link:https://codesandbox.io/s/material-demo-forked-5jcoq?file=/demo.t ...

Applying the Active CSS class to a Bootstrap Carousel

I'm currently working with a bootstrap carousel that displays dynamic images fetched from a backend API. The challenge I'm facing is that I'm unable to set the active class for the individual slides. If I hardcode the active class, all slide ...

Having trouble getting create-react-app to run with "npm start" despite using the correct npm and node versions

I'm currently in the process of learning React by following a helpful tutorial. Recently, I encountered an error regarding a missing start script. After adding it to the package.json file using my text editor, I now find myself at a loss as to how to ...

Error: The mapStateToProps function in React+Redux is returning an undefined

Here's the issue I'm facing: Inside index.js: import {getShowsHome} from './reducers/reducers'; const store = createStore(getShowsHome); ReactDOM.render(<Provider store={store}> <App /> </Provider>, document.getElem ...

Arranging arrows strategically along a line and ensuring they are positioned correctly above all div elements

I'm really struggling with this issue. I have a situation where I need to center a downward pointing arrow within some divs. It should be positioned in the middle, on a brown line, and on top of everything else. The last div should also include the a ...

tips on implementing javascript filter with the id retrieved from an html element in a separate component

I'm having trouble figuring out how to pass the id of the h4 element to the SpecificPost component in order to filter and display only the post with that specific id. This is the first component: render() { var reversedPosts = Object.assign([], ...

Having issues changing image types with onError in react functionality

I am facing an issue trying to display images from our project server as they are saved in four different types (jpg, jpeg, png, and gif) and I do not know which type each image will be. To handle this uncertainty, I wrote the following code within my img ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Nextjs encountered a TypeError stating "Unable to access the 'headers' property of undefined" following an upgrade to nextjs version 12.1.0

After upgrading to Next.js 12.1.0, I encountered an error when calling the api route using aws amplify. The CloudFront console reported the following error: This is my api route: const handlerProducts = async (req: NextApiRequest, res:NextApiResponse) =& ...