Skip to content

alfredosalzillo/style-inject

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

style-inject

NPM version NPM downloads CircleCI donate chat

Inject style tag to document head.

Installation

npm install style-inject

Example

import styleInject from 'style-inject';
const css = `
  body {
    margin: 0;
  }
`;
styleInject(css, options);

Usage with Next (SSR)

If using a library that use style-inject for use css modules in Next.js, you need to inject styles during SSR, here's an example:

// file: pages/_document.js

import React from 'react';
import { SSR_INJECT_ID } from 'style-inject';

const SSRInjectStyles = () => {
    if (!globalThis[SSR_INJECT_ID]) return null

    return (
        <>
            {globalThis[SSR_INJECT_ID].map((module) => (
                <style id={module.id} key={module.id}>
                    {module.css}
                </style>
            ))}
        </>
    )
}

const Document = (props) => {
    const { locale } = props
    return (
        <Html lang={locale}>
            <Head>
                {/* Inject styles during ssr */}
                <SSRInjectStyles />
                {/* ... */}
            </Head>
            <body>
            {/* ... */}
            </body>
        </Html>
    )
}

export default Document

Options

insertAt

Type: string
Possible values: top
Default: undefined

Insert style tag to specific position of head element.

License

MIT © EGOIST

About

Inject style tag to document head.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%