How to style body tag with CSS-in-JS approach?
With Emotion you can set something up, like the following create-react-app example, to inject global styles:
import React from 'react';import ReactDOM from 'react-dom';import { Global, css } from '@emotion/core'const bodyFillColor = `rgb(218,236,236)`;class App extends React.Component { render() { return( <div> <Global styles={css` body { background: ${bodyFillColor}; margin: 0; padding: 0; min-height: '100vh'; max-width: '100vw'; } `} /> <Global styles={{ 'body.noScroll': { // Prevent scrolling; conditionally activate this // in subcomponents when necessary ... overflow: 'hidden', }, }} /> </div> ); }}ReactDOM.render( <App />, document.getElementById('root'));
This shows an example of injecting a style on the body and also assigning a class to the body that can conditionally be activated later on.
eg.
{this.state.activate && <Global styles={{`stylesetc`}}/>}
https://emotion.sh/docs/globals
Alternative
StyledComponents uses a CSS-in-JS approach and works great with React applications. This is a technique I've used in the past straight from the documentation:
import { createGlobalStyle } from 'styled-components'const GlobalStyle = createGlobalStyle` body { color: ${props => (props.whiteColor ? 'white' : 'black')}; }`// later in your app<React.Fragment> <Navigation /> {/* example of other top-level stuff */} <GlobalStyle whiteColor /></React.Fragment>
As per the question if the task is as small as changing body's background color in js then below approach can also be followed any where in your code most probably in App.js
if(theme==='dark') document.body.style.background = '#000'else document.body.style.background = '#FFF'
No need to use a whole styling library for it.
Also i tried editing document.body.style, you can try that too according to below example
if(theme==='dark') bgColor = '#000'else bgColor = '#FFF'document.body.style= `background: ${bgColor}`
Remember following 2nd approach you may overwrite whole body style so please take care of that.
I hope this helps :)