skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    const MyPage = () => {
      // Set the css class
      document.body.setAttribute('class', 'my-class'):
    
      return (
        // Component code
      );
    }
    

    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.


  2. You can directly set inline styles on the <body> element inside the component for each route.

    For example:

    function MyPage() {
        document.body.style.fontSize = '14px';
        // return some JSX...
    }
    

    To reset the style when the component is unmounted, useEffect can be applied.

    import { useEffect } from 'react';
    function MyPage() {
        useEffect(() => {
            const origFontStyle = document.body.style.fontSize;
            document.body.style.fontSize = '14px';
            return () => document.body.style.fontSize = origFontStyle;
        }, []);
        // return some JSX...
    }
    

    You could consider extracting this into a custom hook for more convenient usage.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search