Reputation: 388
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.
Upvotes: 2
Views: 5983
Reputation: 919
You can also achieve this by adding <style>
tag to the component your <Route>
redirects to:
<style>
{`body{background-color: red;}`}
</style>
Upvotes: 1
Reputation: 381
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>
);
}
Upvotes: 3
Reputation: 34
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>
);
}
Upvotes: 0