Search code examples
cssreactjsjss

How to create a global style in React


I'm working on a project for school where one is able to create HTML elements by using Selection.js (visual selection turns into an HTML element). Currently, the user is able to write CSS in a CodeMirror editor. After the user applies the CSS by clicking a button, the styling is directly inserted onto the created React component trough props.

My main goal is to allow the user to create multiple elements with multiple styling rules, to then (in the end) export the created elements along with their styling.

I've imported JSS, because of the createStyleSheet function that generates styling based up on a JavaScript CSS object (which comes from the CodeMirror input) and because of the fact that the directly injected style trough props is not reusable (because it doesn't contain classes, just properties). The problem with JSS is that it generates styling in the form of .mySpecialClass-0-1 {...}

This is the code that I'm using when the user applies the style (on click).

 onStyleInput(e) {
        e.preventDefault();
        try {
            let style= cssToObject(this.codeMirror.getValue(), {camelCase: true});
            this.styleSheet = jss.createStyleSheet(style, {link: true}).attach();
            console.log(this.styleSheet);
        }
        catch (exception) {
            // console.log("Something went wrong, check your css syntax");
            console.log(exception);
        }
    }

The result I expected from JSS was styling in the form of .mySpecialClass {...}, without the unique id's.

I've been looking trough the JSS API, but there doesn't seem to be an available boolean to toggle the unique id generation.

Is there a better way of achieving my goal?

Thanks in advance!


Solution

  • The easiest way to have JSS classes without ID is, make it as "Global" styles. It is mean, we have global CSS styles which not attached individually to the elements. Rather than just put/set HTML className without really utilizing JSS result. They call it "Global selectors" at "plugin" section at their documentation pages.

    You can find documentation here: https://cssinjs.org/jss-plugin-global?v=v10.0.0-alpha.7