Giter VIP home page Giter VIP logo

react-style-tag's Introduction

react-style-tag

Write styles declaratively in React

Table of contents

Installation

$ npm i react-style-tag --save

Usage

// ES2015
import { Style } from 'react-style-tag';

// CommonJS
const Style = require('react-style-tag').Style;

Implementation

import React, { Component } from 'react';

import { Style } from 'react-style-tag';

function App() {
  return (
    <div>
      <h1 className="foo">Bar</h1>

      <Style>{`
          .foo {
            color: red;

            &:hover {
              background-color: gray;
            }

            @media print {
              color: black;
            }
          }
        `}</Style>
    </div>
  );
}

Summary

react-style-tag creates a React component that will inject a <style> tag into the document's head with the styles that you pass as the text content of the tag. Notice above that the styles are wrapped in {`and`}, which create a template literal string. Internally, react-style-tag parses this text and applies all necessary prefixes via stylis. All valid CSS is able to be used (@media, @font-face, you name it), and you can use nesting via the use of the & reference to the parent selector.

The style tag that is injected into the head will be automatically mounted whenever the component it is rendered in is mounted, and will be automatically unmounted whenever the component it is rendered in is unmounted.

Scoped Styles

There is an additional utility provided that can help to scope your styles in the vein of CSS Modules, and this is hashKeys. This function accepts an array of keys to hash, and returns a map of the keys to their hashed values.

import { hashKeys, Style } from 'react-style-tag';

const { foo, bar } = hashKeys(['foo', 'bar']);

function App() {
  return (
    <div>
      <div className={foo}>My text is red due to the scoped style of foo.</div>

      <div className={bar}>
        My text is green due to the scoped style of bar.
      </div>

      <div className="baz">My text is blue due to the global style of baz.</div>

      <Style>{`
          .${foo} {
            color: red;
          }

          .${bar} {
            color: green;
          }

          .baz {
            color: blue;
          }
        `}</Style>
    </div>
  );
}

Notice you can easily mix both scoped and global styles, and for mental mapping the scoped styles all follow the format scoped__{key}__{hash}, for example scoped__test__3769397038. The hashes are uniquely based on each execution of hashKeys, so the implementation can either be Component-specific (if defined outside the class) or instance-specific (if defined inside the class, on componentDidMount for example).

Props

Naturally you can pass all standard attributes (id, name, etc.) and they will be passed to the <style> tag, but there are a few additional props that are specific to the component.

hasSourceMap

boolean, defaults to false in production, true otherwise

If set to true, it will render a <link> tag instead of a <style> tag, which allows source referencing in browser DevTools. This is similar to the way that webpack handles styles via its style-loader.

The use of sourcemaps require the use of Blob, which is supported in IE10+, Safari 6.1+, and all other modern browsers (Chrome, Firefox, etc.). If you browser does not support Blob and you want to use sourcemaps, you should include a polyfill. Recommended is blob-polyfill.

Make sure this import occurs prior to the import of react-style-tag to ensure blob support is present.

isMinified

boolean, defaults to true in production, false otherwise

If set to false, it will pretty-print the rendered CSS text. This can be helpful in development for readability of styles.

isPrefixed

boolean, defaults to true

If set to false, it will prevent stylis from applying vendor prefixes to the CSS.

Global Options

All of the props available are also available as global options for all instances that can be set with the setGlobalOptions method:

import { setGlobalOptions } from 'react-style-tag';

setGlobalOptions({
  hasSourceMap: true,
  isMinified: true,
  isPrefixed: false,
});

Development

Standard stuff, clone the repo and npm i to get the dependencies. npm scripts available:

  • build => run rollup to build dist files
  • dev => run webpack dev server to run example app / playground
  • dist => runs build and build:minified
  • lint => run ESLint against all files in the src folder
  • lint:fix => runs lint with --fix
  • prepublishOnly => run lint, typecheck, clean, test, transpile:es, transpile:lib, and dist
  • test => run jest test functions with NODE_ENV=test
  • test:coverage => run test, but with coverage checker
  • test:watch => run test, but with persistent watcher
  • transpile:lib => run babel against all files in src to create files in lib
  • transpile:es => run babel against all files in src to create files in es, preserving ES2015 modules (for pkg.module)
  • typecheck => check for TypeScript errors

react-style-tag's People

Contributors

dependabot[bot] avatar hgcummings avatar oasisvali avatar planttheidea avatar tquetano-netflix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-style-tag's Issues

move `hasSourceMap` and `isMinified` to static?

I'm not really sure of this, but isn't it better to have hasSourceMap and isMinified as static properties so to not have to explicit them for every instance? E.g.

// before loading any other styles
import Style from 'react-style-tag';
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
Style.hasSourceMap = !IS_PRODUCTION ;
Style.isMinified = IS_PRODUCTION;

Warning: componentWillUpdate has been renamed, and is not recommended for use

Warning: componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.

  • Move data fetching code or side effects to componentDidUpdate.
  • Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: Style

image

ReferenceError: process not defined

I’m getting this when using Webpack 5 in constants.js.

Have tried using DefinePlugin to set process.env.NODE_ENV but it doesn’t help.

It throws at that point and nothing renders.

Warning: componentWillUpdate has been renamed

Hello,

When I render the component I get in my console a warning.

`Warning: componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.

  • Move data fetching code or side effects to componentDidUpdate.
  • Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: Style`

Is that something I should be concerned about or will it be fixed?

Thank you

Support for global autoprefixer config ?

From the code, it appears that there is no way to pass in a autoprefixer config (such as browsers) for the component. I could see this being useful for our project where we support a very specific set of browsers (defined in our browserslist) and we would like to share that config for the autoprefixer with this component.

If this is something that makes sense to add to this project, I can get a PR going 😄

Typescript types?

It would be helpful to have a .d.ts file or a @types/react-style-tag npm module.

[question] why <style> does not appear twice?

Let me tell you this is really nice piece of code :-)

I already do something similar in rioct-cli / react-templates (where the <style> tags are processed at compile time) but studying your code suggested me two or three improvements I can do, so a big thank you.

A question: I noticed the component generates a <style> tag that is also appended to the document.head. So I was expecting to find two style tags, one in the head and one in the component, but inspecting the DOM the one in the component is missing. How do you achieve that?

BTW, I would like to import your minify(cssText) function, is it going to stay? or perhaps can a module be made out of it?

One last remark: npm run dev fails in Windows, had to use instead:

node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --progress --colors --config=webpack.config.dev.js

Export a separate component without prefixing.

Currently the style component includes an option for not prefixing code. This is great! Prefixing may not be required in all circumstances, and the bloat to the bundle for on-the-fly prefixing is significant.

I am proposing a separate component without prefixing, as even with the prop set to disable prefixing, using the component adds an untenable amount of code to generated bundles. Even if you are not using prefixing in your application, including the <Style /> tag will add the entirety of caniuse-db to your bundle, as it is imported regardless.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.