How can I add style to the body element with JSS?

Viewed 5235

I'm building an application using react-jss to style my components and wanted to know if it is possible to add styles to top-level elements (like html or body).

To illustrate, I have this simple NotFound component that I'm styling with react-jss. The style works fine, but the problem is the body elements has a default margin that I wanted to remove.

NotFound.js

import React from 'react';
import injectSheet from 'react-jss';

const styles = {
    notFound: {
        fontFamily: 'Roboto',
        backgroundColor: 'blue',
        color: 'white'
    }
}

function NotFound({ classes }) {
  return (
    <div className={classes.notFound}>
      NOT FOUND
    </div>
  )
}

export default injectSheet(styles)(NotFound);

enter image description here

Does anyone know if its possible to remove this margin using css-in-js? (I wanted to avoid css)

2 Answers

You can use the syntax introduced by jss-plugin-global

  '@global': {
    body: {...}
  }

Also recommend creating a separate component for this and wrap your component with it. Otherwise your specific component becomes less reusable.

Just to elaborate Oleg's response, that's what I did:

1.Create my own JssProvider. Note: Had to also add jss-plugin-camel-case otherwise it wouldn't parse my properties from camelCase to lisp-case:

import App from './App';
import { create } from 'jss';
import { JssProvider } from 'react-jss';
import globalPlugin from 'jss-global';
import camelCase from 'jss-plugin-camel-case';

const jss = create();
jss.use(globalPlugin(), camelCase());

render(
    <JssProvider jss={jss}>
        <Router>
            <App />
        </Router>
    </JssProvider>
    document.getElementById("app")
);

2.Added my global property to my top level component

import React from "react";

import Main from "./common/ui/components/Main";
import NotFound from "./components/NotFound";
import injectSheet from 'react-jss';

const style = {
    '@global': {
        body: {
            margin: 0
        }
    }
};

const App = () => {
    return (
        <Main>
            <Switch>
                <Route component={NotFound}/>
            </Switch>
        </Main>
    );
};

export default injectSheet(style)(App);

And that was it! Worked like a charm.

EDIT: After some more research I found that I don't need step 1. Just adding the @global style to my App component did the job. I guess this jss-global plugin must be default in react-jss. (someone correct me if I'm wrong)

Related