What is the best way to incorporate unique body CSS for various pages within a ReactJS application?

I am currently in the process of developing a multi-page website and faced with the challenge of applying different CSS styles to the body based on the specific page.

My approach involves using react-router-dom for handling routing, and my file structure is organized as follows:

Main.js

import React from 'react';
import { Routes, Route } from 'react-router-dom';

// Additional imports for individual pages go here

const Main = () => {
  return (
    <Routes>
      <Route exact path="/" element={<MyPage />}></Route>
      <Route exact path="/another" 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>
);

Answer №1

One way to customize the styles of the <body> element within a component is by setting inline styles directly.

For instance:

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

To ensure that the style is reset when the component is no longer rendered, you can utilize useEffect.

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

For easier implementation, you may want to create a custom hook for this purpose.

Answer №2

After much experimentation, I stumbled upon a workaround that may not be standard practice, but it gets the job done.

My solution involves setting the body class at the start of each page component before rendering it.

Here's an example:

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

  return (
    // Component code
  );
}

The only downside is that I have to repeat this process for every individual page component to prevent one component's body CSS from affecting another.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with alignment on the printed version of an HTML document

While attempting to print an auto-generated HTML page through my Thermal POS printer, I encountered a large left margin issue. The application is developed using PyQt5, and I had to resort to a python script to generate the HTML code. Unfortunately, in the ...

What is the reason behind the lack of access for modal to an external controller?

Imagine having this code in your main HTML file: <body ng-app="app" ng-controller="session as vmSession"> ... <!-- Modal content goes here --> </body> Inside the modal, you have a link: <a ui-sref="siteManagement({ site: vmSession.u ...

Submit button failing to fire upon clicking

I have recently started working with AngularJS and I'm facing an issue regarding ng-submit not getting triggered when trying to submit the form. Additionally, I am having trouble accessing $scope.user which is preventing me from posting to the server. ...

Are Django form widgets like datepicker and tabindex being snubbed?

I have been working on creating a stylish form and managed to find some interesting CSS to enhance it. The form is looking good, however, a couple of fields are not displaying correctly; particularly one that is associated with a choice field as the model ...

Angular date picker

I am using a datepicker with Angular. Here is my question: Is there a way to prevent the user from manually typing in the input field? I only want to allow the user to select a date from the pop-up calendar. ...

JavaScript is unable to bring in an npm module

Having trouble importing an npm module using import fs from 'fs'; in my main.js file that is linked with index.html. The script tag connecting the JS file has the attribute type="module". However, the browser console shows the error: Un ...

Fullcalendar Bootstrap popover mysteriously disappears

I'm having issues with my Bootstrap popovers being hidden under the rows in FullCalendar. I've tried using container: 'body' and trigger: 'focus', but they don't seem to work. The function that's causing this proble ...

Preventing the reoccurrence of function events

I need to create an event triggered by a mouse click when the user clicks a button. The code snippet below shows my attempt, but I'm facing an issue where the function continues to run if the user clicks on a second input field after the initial one: ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

Doesn't the use of asynchronous programming in Node.js lead to a potential StackOverflow issue?

Recently, I identified an issue with the Node.js (single-threaded) platform: As requests are handled by the server and they undergo processing until being blocked due to I/O operations. Once a request is blocked for processing, the server switches ba ...

Execute a setInterval operation, pause it for a duration of 3 seconds, and then resume its execution

A setInterval function is looping through some div classes, and if it encounters a div with a specific class, it should pause for 3 seconds before resuming. I am using the following code to clear the interval: clearInterval(myInterval); However, I nee ...

The WebSocket connection encounters issues when trying to facilitate internal communication within a Kubernetes container

Utilizing Kubernetes for the deployment of my React Application, I am integrating it with a (RethinkDB) database. The task involves establishing a WebSocket connection between the React Application and a Node.js server that serves as a proxy to the Databas ...

Tips for integrating Apache Solr with Cassandra without using DataStax Enterprise (DSE)

Embarking on a new project, I find myself utilizing Cassandra as the chosen DBMS, with Apache Solr serving as the search engine and Node.js powering the server scripting language. While I am well-versed in Node.js, Cassandra and Solr are unfamiliar territ ...

Is there a workaround for retrieving a value when using .css('top') in IE and Safari, which defaults to 'auto' if no explicit top value is set?

My [element] is positioned absolutely with a left property set to -9999px in the CSS. The top property has not been set intentionally to keep the element in the DOM but out of the document flow. Upon calling [element].css('top') in jQuery, Firef ...

Show information stored in a database table in an HTML table format using PHP

Within my "enchere" database, there exists a table named Produit. The goal is to exhibit the information stored within the produit table: Nom_produit, description_produit along with the product's image. The image itself is located on a server, in thi ...

Turn off the Antd Datepicker tooltip

I'm using Antd Datepicker in my website. We get an array of numbers representing disabled dates from an external api and show only the dates in the datepicker(no month, year etc). The date selection is for a monthly subscription and the user just sele ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...

What is the purpose of the bold line down the left side of every HTML calendar?

Welcome to a calendar layout designed with flexbox: Check it out here Do you notice the thicker lines below the heading rows and want to remove them? Here is how you can modify the HTML & CSS code: #calendars-container { text-align: center; font-f ...

Uncovering the websocket URL with NestJS and conducting postman tests: A step-by-step guide

Creating a mean stack application using NestJS involves utilizing websockets. However, testing websockets in Postman can be confusing. Typically, I test route URLs in Postman and get output like: "http://localhost:3000/{routeUrl}". But when it comes to tes ...

Creating dynamic rows for Firebase data in React BootstrapTable can be accomplished by dynamically rendering each row

Hey everyone, I'm currently working on a web app project where I am creating a table. Below is the code snippet for it: class Table1 extends Component { render() { return ( <div> <BootstrapTable data={this.props.data}> ...