Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent white screen during initial loading of React app?

function App() {
  return (
    <>
      <div
        style={{
          width: "100vw",
          height: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          backgroundColor: "black",
        }}
      >
        <Logo3 />
      </div>
    </>
  );
}

The App is as simple as above. The background is supposed to be black, but sometimes there is an initial white screen that appears for a split second before the app is loaded. How this white screen be prevent?

like image 297
Big Cat Public Safety Act Avatar asked Nov 19 '25 07:11

Big Cat Public Safety Act


2 Answers

So the easiest way to do this is to just set a background color for the body of your page within your html-file. This way there is an initial background color and you won't experience the flash when (re-)loading the website.

<style>
    body {
      background-color: black;
    }
</style>

The other more complex solution is to use server-side-rendering. The idea is to let the server serve an initial version of the DOM. This DOM will be diffed and altered by react after all the JavaScript code is loaded and evaluated.

Take a look at

ReactDOMServer.renderToString(reactElement)

and

ReactDOM.hydrate()

if you are using a Node-Backend.

like image 196
Andreas.Ludwig Avatar answered Nov 21 '25 21:11

Andreas.Ludwig


Below is a cleaner way I think, just go to your index.html file or whatever your React app is using and add a style tag into the initial <html .. /> tag

Replace #111 with your preferred dark color.

E.g.

<html lang="en" style="background-color: #111">

This will be overridden as your app styling is loaded.

like image 30
Ian Smith Avatar answered Nov 21 '25 21:11

Ian Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!