I’m making a multi-page website and trying to add different CSS to the body for different pages.
I’m using react-router-dom
to handle routing, and I have my files set up like this:
Main.js
import React from 'react';
import { Routes, Route } from 'react-router-dom';
// Other imports for pages here
const Main = () => {
return (
<Routes>
<Route exact path="/" element={<MyPage />}></Route>
<Route exact path="/" element={<AnotherPage />}></Route>
</Routes>
);
}
export default Main;
App.js
import './App.css';
import Main from './Main';
const App = () => {
return (
<div className="App">
<Main />
</div>
);
}
export default App;
index.js
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
2
Answers
So I figured out a solution, though not sure if it's good practice, but it works.
I set the body class at the beginning of each page component, before returning it.
For example:
Only thing is, I have to set this on every single page component, to ensure the body CSS of one component doesn't carry into another.
You can directly set inline styles on the
<body>
element inside the component for each route.For example:
To reset the style when the component is unmounted,
useEffect
can be applied.You could consider extracting this into a custom hook for more convenient usage.