2

Does anyone know how to style the root in React? I know it can be done in JQuery by executing the following;

$(":root").css("background-color", "yellow");
Naramsim
  • 8,059
  • 6
  • 35
  • 43
Guy Lepage
  • 95
  • 1
  • 3
  • 12

2 Answers2

2

Here is an example,App is my root element.

import './App.css';
class App extends Component {

  render() {
    const backStyle = style({
      background: 'black'
    })
    return (
      <div className={backStyle}>
      ...
      </div>
    );
  }
}

export default App;

You define the css properties like background-color in App.css. And there are many ways to do that.

return (
  <div style={{background: black}}>
  ...
  </div>
);

Define the style of the root is quite similar.i.e

import './index.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
Root
  • 2,301
  • 1
  • 10
  • 14
  • I am actually looking to define the style in Javascript inline in the `index.js`. I am currently styling the root in my imported `.css` file. The reason for this is that when I save my app on my iPhone as a "Save to Home Screen" app and then open the app there is an initial white screen that appears before the app displays. I am trying to ensure the initial launch background color is black. – Guy Lepage Oct 17 '18 at 13:38
  • I have made a change to my answer. – Root Oct 17 '18 at 13:45
  • I'm actually trying to define the core root actually.. `ReactDOM.render( , document.getElementById('root') );` – Guy Lepage Oct 17 '18 at 14:04
  • I have change my answer.@GuyLepage – Root Oct 18 '18 at 08:15
  • The `#root` element in your answer is not the same as the `:root` selector in the question. In html, the `:root` selector is actually the element. – DarkAngel Jul 14 '22 at 08:18
1

You can do one thing. In your index.html you can use style tags to style root div. It will do what you are trying to do. As all the components are loaded within the root wrapper, so it will be like a global style.

Himanshu Tariyal
  • 264
  • 6
  • 13