What is the best method for styling the "body" of multiple pages in a React.js application to prevent them from overlapping?

Hello everyone,

After attempting different approaches in numerous ways, I have turned to the experts here who are sure to have the answer to this simple problem.

The issue at hand is that when I try to apply background images and other properties to the "body" of different pages within the app I am creating, it only applies the CSS of one page to all others.

To simplify my question:

How can I add distinct styles for the body tag across multiple pages?

For your convenience, you can refer to the code snippet below:

Here's the Login file

import React, { Fragment, useState } from 'react';

import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { login } from '../../../actions/auth';

import './Login.css';

...


const Login = ({ login, isAuthenticated }) => {

    ...

}


Login.propTypes = {
    
    ...
};

...

export default connect(mapStateToProps, { login })(Login);

Its css file

html,
.Login>.bodyLogin {

    ...

}


.Login>.bodyLogin {

    ...

}

Currently, I want to incorporate different background images for other pages. However, I keep getting the same image as used in Login.js.

Modules did not yield desired results. Is there a proven method to address this issue?

I attempted adding the following functional component like this:

const Login = ({ login, isAuthenticated }) => {

    useEffect(() => {
        document.querySelector('body').style.backgroundImage = url("../../../images/undraw_people_tax5.png");
    })
}

However, I encountered a red error message which halted my progress!

https://i.sstatic.net/Fn2vy.png

Answer №1

If you need to control markup outside of React, the recommended practice is to use a library called React Helmet.

For each component, include a Helmet element to define body styles and other attributes. Here's an example:


import Helmet from 'react-helmet';
function Page(props) {
    const bgColor = '#ddd';
    return (
       <div class="page">
                <Helmet>
                    {/* Define inline CSS for body tag */}
                    <body style="background-color: #ddd" />
                    {/* Or include in-file CSS */}
                    <style>
                       {`
                            body {
                                background-color: ${bgColor};
                            }
                       `}
                    </style>
                </Helmet>
                {/* Rest of your component content goes here ... /*}
       </div>
    );
}

You can nest multiple instances of Helmet within each other, allowing for customization of the body at different levels deep within your component hierarchy.

Please note that this approach is best suited for defining CSS on elements outside of React like html or body. For styling within React components, consider using better methods such as CSS Modules or Styled Components.

Update 1

In your specific case, ensure that the Helmet component is the first child of the <Fragment>:

     <Fragment>
         <Helmet>
             <style>
                {`
                   html, body {
                       height: 100%;
                  }

                 body {
                    background-image: url("/client/src/components/images/undraw_people_tax5.png"), url("/client/src/components/images/undraw_together_j0gj.png");
                    background-size: 80% 100%, 101% 100%;
                    background-repeat: no-repeat;
                    background-position: 1% 60%, 80% 110%;
                  }
                `}
            </style>
         </Helmet>
       {/* Rest of your Fragment goes here ... /*}
     </Fragment>

Update 2

If you prefer to use a CSS file instead of writing everything inline, you can replace your import './Login.css') statement with the following:

 const css = require('./Login.css').toString();

Then simply include the CSS string within the <style> tags in your Helmet component:

                <Helmet>
                    <style>
                        {css}
                    </style>
                </Helmet>

Answer №2

Consider using unique class names for each section and avoid applying global styles to individual pages. Instead, encapsulate each page within its own container, containing all necessary elements and styles. This strategy can streamline your design process and enhance organization. Give it a try!

Answer №3

Please include the following code snippet in every component:

For class-based components:

componentDidMount() {
   document.querySelector('body').style.backgroundImage = 'url(/* add image path here */)';
}

For functional components:

useEffect(() => {
   document.querySelector('body').style.backgroundImage = 'url(/* add image path here */)';
}, []);

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

The elements at the bottom of the Google homepage do not stay in place when hovering

I'm facing an issue and seeking guidance on how to make the footer and 'Google in different languages' fixed when hovering over the buttons. I'm attempting to create this on my own without referencing the Google homepage code in Chrome ...

Tips for customizing the height of the select component in React Material UI

Currently, I am working on a select component that has a fixed height which cannot be decreased. You can see the screenshot below: https://i.sstatic.net/UtfXd.png The issue I am facing is that I want the height of the Select component to match that of th ...

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

Tips for utilizing FixedHeaderTable - Basic instructions required

After doing extensive research, I stumbled upon this plugin called Fixed Header Tables. Despite following the instructions provided on the main website, I couldn't get it to work. I was aiming to create a table with a fixed top row and left column fu ...

Error encountered when attempting to show result using React Hooks

When a button is clicked, I want to display more information about a specific item from a list. To achieve this functionality, I have utilized a hook that fetches all the items from an API and lists them iteratively within a <ul> tag (inside the retu ...

The text displayed on the image is experiencing fluctuations

I am experiencing an issue on my website where the post text fluctuates rapidly when the mouse hovers over the image. I have a site where I display the post text on mouseover of the image. Can someone please help me solve this problem? You can test it by ...

Is it possible to run the npm start command in the background using PHP and continue with the next line of code?

I'm currently working on a major project that involves using PHP Laravel for the backend and React for the frontend. The goal is to upload a zip file containing a React project, extract it, run the npm start command to initiate the server, and then us ...

Hiding overflow when navigating back a page in Safari

I need help finding a solution to this issue. On my website, the results page works perfectly fine until I navigate to a product's details page and then return to the results using the "page before" button. At that point, the overflow becomes hidden, ...

"Angular 6: A Guide to Customizing Text Colors Based on Status

I have a view on angular just like this: https://i.sstatic.net/JimWN.png And this is my dashboard.component.ts: export class DashboardComponent implements OnInit { tablePresetColumns; tablePresetData; ngOnInit() { this.tablePresetColumns = [{id: ...

Combining two arrays in React using TypeScript and showcasing them in a single list display

I am working on a React TypeScript project and have two comma-separated strings that I am converting into arrays. One array contains the file names, and the other contains the file link paths. My goal is to merge the two arrays so that the first item in th ...

Every time I attempt to build a React application, I encounter an unexpected error

After running the command to install create-react-app, I encountered a strange error message when trying to create a new React app with the create-react-app name command: C:\Users\Mostafa Ossama\Desktop>create-react-app swag-shop-web Cr ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

Exploring tabs functionality with Material UI, Jest, and Enzyme testing

I am currently testing a component with tabs. My initial test is to verify the correct initial state, followed by testing whether clicking on another tab changes the state. The technologies I am using for this are material-ui, jest, and enzyme. import Rea ...

What is the method to have the text cursor within a text field start a few pixels in?

I need a text field with the cursor starting a few pixels (let's say 4) from the left-hand side. I am aware that this can be achieved by adjusting the size of the text field using padding, but I am curious if there is a way to resize the text box with ...

Exploring matching routes with Next.js + Jest

Issue with Unit Testing MenuItem Component Despite my efforts to achieve 100% coverage in my component unit tests, I have encountered an uncovered branch specifically within the MenuItem component. To offer more insight, here is the parent component that ...

What is the best way to organize the table by date when not all dates are filled in?

**Issue with React-Table Sorting:** I'm encountering an issue with my React-Table implementation. I am using version 7 of the plugin. { Header: 'DATE', accessor: 'DATE', sortType: (rowA, rowB) => { ...

Problem with responsive design on iPhone

I'm currently working on developing a responsive chatbot using CSS Bootstrap. However, I've encountered an issue where the header and footer are not fixed when I open the app on an iPhone. The keyboard header is also moving up the screen, which s ...

Organizing product categories in React

Can anyone assist me in sorting an array with currencies in a React application? I am currently rendering a list of products, each containing a price block. The data structure consists of an array of products, with each product having a subarray of prices ...

Select a Month and Year with Material UI React

Can we create a month and year picker using Material UI that displays only the month and year (e.g. 2020-09) in the output? ...

A div positioned in front of a centrally-located div

Managing a website with numerous headlines can be a challenge. When a user clicks on a headline, a button located 10px to the left of the headline should appear. However, the catch is that the headlines must always remain centered, regardless of whether th ...