Home > database >  How do I change the whole page background color with each route using React?
How do I change the whole page background color with each route using React?

Time:02-06

Im building a react app and I want every route to have a different background color. But the only way to change the background color of the whole page is by using the * {} tag. Is there some kind of theme library or anything I can do to pass a variable from my routes to the * {} tag to change its background color?

Other solutions would include putting a min-height on my root component but that just feels wrong and I will not do it.

CodePudding user response:

You can use a state color and pass it to each Route. This is an exemple to illustrate what i ve told you :

function App() {

  const [color, changeColor] = useState("#282c34");
  return (
    <div style={{ background: color }} id="main">
      <Router>
        <div>
          <nav>
            <ul>
              <li>
                <Link to="/" onClick={() => changeColor("#282c34")}>
                  Home
                </Link>
              </li>
              <li>
                <Link to="/about/" onClick={() => changeColor("#9c27b0")}>
                  About
                </Link>
              </li>
              <li>
                <Link to="/users/" onClick={() => changeColor("#007bff")}>
                  Users
                </Link>
              </li>
            </ul>
          </nav>
          <Route path="/" exact component={Index} />
          <Route path="/about/" component={About} />
          <Route path="/users/" component={Users} />
        </div>
      </Router>
    </div>
  );
}

CodePudding user response:

I think you can use this as well

    function App() {
    
      const [color, changeColor] = useState("#282c34");

      document.body.style.backgroundColor = color;
      
      return (
        <div>
          <Router>
            <div>
              <nav>
                <ul>
                  <li>
                    <Link to="/" onClick={() => changeColor("#282c34")}>
                      Home
                    </Link>
                  </li>
                  <li>
                    <Link to="/about/" onClick={() => changeColor("#9c27b0")}>
                      About
                    </Link>
                  </li>
                  <li>
                    <Link to="/users/" onClick={() => changeColor("#007bff")}>
                      Users
                    </Link>
                  </li>
                </ul>
              </nav>
              <Route path="/" exact component={Index} />
              <Route path="/about/" component={About} />
              <Route path="/users/" component={Users} />
            </div>
          </Router>
        </div>
      );
    }
  •  Tags:  
  • Related