score:-10

Accepted answer

It's been a while since I asked this question. What I've started doing since then is using Facebook's create-react-app setup, and editing CSS files directly.

score:-1

Make a wrapper componenet with an id like "wrapper" and then create a style with the color state:

getInitialState: function () {
  return { color: "white" }; // Set your color for initial state.
},

changeColor: function () {
  this.setState({ color: "black" }); // Set your changed color.
},

render: function () {
  var style = { backgroundColor: this.state.color };
  // The wrapper (root) component
  return (
    <div id="fullscreen" style={style}>
       <a onClick={this.changeColor}>change</a>
    </div>
  );
}

The result should be something like:

<body>
    <div id="fullscreen" style="background-color: YOUR CUSTOM COLOR">
        <a onclick="THE REACT FUNCTION"></a>
    </div>
</body>

score:0

This was simplest solution for me:

// in your css file

.background-white {
    background-color: white !important;
}


// in your react component

componentDidMount() {
    document.body.classList.add("background-white");
}

componentWillUnmount() {
    document.body.classList.remove("background-white");
}

Using componentWillMount did not work reliably. Using document.body.style did not work reliably either.

score:0

If you are using React with Bootstrap, just include a background-color Bootstrap class to the <body> tag, in the index.html file, like this:

<body class="bg-light">

You can choose other colors from https://getbootstrap.com/docs/4.3/utilities/colors/#background-color

score:0

In your react src folder you should have a custom.css file.

Add 'body {background-color: ; }' in that custom.css file.

score:0

By default, assuming you've used npx Create-React-app MyAppName your React app will have an index.css.

This contains css which controls the default grey background. Just edit this to what you require.

body {
  margin: 0;
  background-color: #3f3f3f; 
}

score:0

create index.css file like this

body {
  margin: 0;
  background-color: rgba(0, 0, 0, 0.07);
}

Then import it in your index.ts file

import "./index.css";

Also keep in mind the background color property might get overwritten if you import other css files below

So your index.ts file look like this

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap/dist/css/bootstrap.css";
import "./index.css";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

score:0

This works for me as long as my body's data has content in it

body { background-color : rgba(235,232,232,0.767); }

Similarly, you can alter the root tag as well.

#root{ background-color: rgba(235, 232, 232, 0.767); }

score:0

If you want to change background color before the page loads you can do something like this.

import React, { useLayoutEffect } from 'react'
useLayoutEffect(() => {
     document.body.style.backgroundColor = "red"
});

For further reference on useLayoutEffect check here

score:1

Please Don't need to install any packages is very easy and simple ! add

 document.body.style = 'background: red;';

to your JS code or via CSS like below:

const Changebackground = () => {
  const stylesObj = {
    background: "green"
  };

  return ( <
    div id = "hello-world"
    style = {
      stylesObj
    }
    className = "container" >
    <
    /div>
  )
}
export default Changebackground;
//ReactDOM.render( < Changebackground / > , document.getElementById('App'));
.container {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: -10;
  text-align: center;
  transition: all 500ms ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>

please check this one to see how its easy ! https://codepen.io/farbod-aprin/pen/dadJyb

score:1

You can use a CSS module in React. Below is the Javascript code for a file named Home.js

import styles from './Home.module.css';

const Home = ()=>{
    return(

        <div className = {styles}>

        </div>
    );

}

export default Home;

And in a css module named Home.module.css (format is [name].module.css), put the following and your page will have a background colour of blue

body{
    background-color: blue;
}

score:1

The style property is not writable in Typescript but setAttribute works okay. Just pop it in your App component. It may not be a good idea to have a random bit of styling outside of React's many other styling mechanisms, it might make it hard to find, but if it's what you need it's what you need. It's what I needed today anyway!

    document.body.setAttribute('style', 'background: red;')

score:1

I faced this issue too and this is my solution.

body{
   margin:0;
   background-color:blue;
 }

score:2

I just fiddled around with this for a bit. Simple solution for me, not entirely intuitive, all in public/index.html:

<html style="background-color: red">

that gets the bottom of the page, and a second entry:

<body style="background-color: red">

that gets you the top of the page ie. your react code.

Two entries for one problem but it's all in one file, needs no new libs and seems to work.

score:2

After some time scouring the internet, I found this solution on a now deprecated github repo:

document.body.style.backgroundColor = "INSERT_COLOR";

You can post it outside of your function (That's how I used it)

It worked for me in my project: https://github.com/antdke/styled-input-bar/blob/master/src/App.tsx

I needed it to color the background for the entire app.

Where I found the code snippet (At top of the README.md): https://github.com/happylinks/react-body-backgroundcolor

Hope it helps you all out like it helped me :)

score:2

You should have a root component (e.g., a div) that is affected by the color you want as the background. That's the react-way to think about it.

  <div className ="bg-primary"> // this should cover everything in the background 
    <div className="container mx-auto bg-secondary"> // this could be a centered container that has a different color.
      <MyReactComponent />
    </div>
  </div>

score:3

The basic idea is to use the browser API in raw JavaScript without installing any packages. I don't recommend to use Helmet because it is unsafe to the life cycle of a class component.

// Update the document body background using the browser API
// in render() function for class component or directly in functional component
document.body.style.background = 'red';

Other application:

If you are constantly changing the body's background color, and you want to have the code to run on every render, following is an example. Be careful where you call the browser API.

For a class component, update it in componentDidUpdate().

import React from 'react';

class Example extends React.Component {
  // ...
  
  componentDidUpdate() {
    // change background color with a random color
    const color = Math.floor(Math.random()*16777215).toString(16);
    document.body.style.background = color;
  }

  // ...
}

For a functional component, using Effect Hook useEffect(). You can look more into React Hook here.

import { useEffect } from 'react';

function Example() {
  // ...

  // Similar to componentDidMount and componentDidUpdate in class component:
  useEffect(() => {
    // change background color with a random color
    const color = Math.floor(Math.random()*16777215).toString(16);
    document.body.style.background = color;
  });

  // ...
}

score:12

React Helmet (https://github.com/nfl/react-helmet)

I really found this library very helpfull. Really clean solution i would say.

Sample Usage:

import Helmet from 'react-helmet';

<Helmet bodyAttributes={{style: 'background-color : #fff'}}/>

score:13

The above solutions tell about adding the external library to give the required functionality but instead what you can do is just go to your Index.css file and inside the already written 'body' tag put "background-color: 'color'" and its done

score:21

try this to your code

componentDidMount() {
    document.body.style.backgroundColor = "red"
}

Hope to help.

score:24

The simplest solution without doing anything fancy is to:

1) Open public/index.html

2) Add an inline style to your body like this: <body style="background-color: red">

score:43

The simplest solution is a bit hacky, but you can use raw javascript to modify the body style:

document.body.style = 'background: red;';
// Or with CSS
document.body.classList.add('background-red');

A cleaner solution could be to use a head manager like react-helmet or next.js Head component.

import React from 'react';
import {Helmet} from 'react-helmet';

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <style>{'body { background-color: red; }'}</style>
            </Helmet>
            ...
        </div>
    );
  }
};

Some css-in-js also offers tools to manage global level styles; like styled-components injectGlobal.

In the end, there's a lot of tools providing cleaner ways to handle this. But if you don't want to rely on third party, the raw JS option might be good enough if you don't make it too interactive.


Related Query

More Query from same tag