Tips for dynamically changing the body class based on the page in a remix

I am trying to set parameters for the body class in root.jsx, which will change based on the page being viewed. I want to assign different values to the class in each route - for example, in _index it should be "company homepage", and in the restaurants route it should be "venue company", and so on. Is there a way to pass parameters from routes to root.jsx?

root.jsx


export default function App() {
  return (
    <html lang='en'>
      <head>
        <meta charSet='utf-8' />
        <meta name='viewport' content='width=device-width, initial-scale=1' />
        <link rel='preconnect' href='https://fonts.googleapis.com' />
        <link
          rel='preconnect'
          href='https://fonts.gstatic.com'
          crossOrigin='anonymous'
        />
        <link
          href='https://fonts.googleapis.com/css?family=Montserrat:wght@100,300,400,500,700&display=swap'
          rel='stylesheet'
        />
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <ScrollRestoration />
        <Scripts />
        <LiveReload />
      </body>
    </html>
  );
}

_index.jsx


export default function Index() {
  const { startPage } = useLoaderData()
  const page = startPage.page.sections;
  return (
    <main id='main'>
      <PageComponents page={page} />
    </main>
  );
}

restaurants.jsx

export default function Restaurants() {
  const { restaurants } = useLoaderData();
  return (
    <>
      <PageComponents page={restaurants.sections} />
      <footer className='footer' />
    </>
  );
}

PageComponents.jsx

import loadable from "@loadable/component";

const components = {
  logo: loadable(() => import("./Logo")),
  intro: loadable(() => import("./Intro")),
  languageSwitch: loadable(() => import("./LanguageSwitch")),
  venueGroup: loadable(() => import("./VenueGroup")),
};

export default function PageComponents({ page }) {
  return (
    <main>
      {page
        .filter(({ type }) => !!components[type])
        .map(({ data, type }) => {
          const Component = components[type];

          return (
            <div key={type}>
              <Component data={data} />
            </div>
          );
        })}
    </main>
  );
}

Tried implementing a loader function in root.jsx to fetch API data for each page and include a variable for the body's className, but sometimes there may not be any data available about the pageClassName. In such cases, I need to manually pass the className parameter to each page from the routes and then transfer this parameter to root.jsx.

Answer №1

To streamline the process, you can create an object that maps CSS files to URL paths and utilize the useLocation hook to determine which child component is currently being displayed.

import { useLocation } from "@remix-run/react";

function SomeComponent() {
  const location = useLocation();
  // ...
}

Instead of modifying CSS directly from the parent component, it's recommended to assign different CSS files to individual components. Making changes to the parent's CSS file every time a child component renders can impact app performance and goes against React's optimization principles. If your website consists of distinct child pages under the same theme, maintaining consistency in the parent's layout elements like the Header and Footer across all pages aligns with good design practices.

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

How to send data to Material-UI drawer components

In the component called Setup, there are input fields that each hold their own data stored in an object named dropdowns. Alongside each input field, there is a drawer component containing the ID of that specific input field. I have a function called handle ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

Looking to turn off animation for a WordPress theme element?

Is there a code that I can insert into the style.css file to deactivate the theme animations on my WordPress page? As users scroll down, each element either drops in or slides in. I recently purchased the WP Alchemy theme from , but the animation speed is ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

Using jQuery to encode an ampersand in a URL

I am facing an issue where some URLs with & in them need to be converted to HTML entities using jQuery. The original code looks like this: <div id="box"> <a href="http://domain.com/index.html&location=1">First URL</a> &l ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

The radio button's checked attribute fails to function

I am currently working on adding a hover effect to radio button labels, and while it is functioning correctly, I would like to achieve the following: When a radio button is selected, I want the corresponding label to have a background color. Despite tryi ...

Using ValidationGroup to trigger JavaScript calls from controls

Is it possible to trigger a JavaScript function from the "onclientclick event" of a button that has a ValidationGroup assigned? <asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" ValidationGroup="Valid ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Enhancing an Image Gallery using CSS

Currently in the process of building a website for an upcoming event, and naturally, I need to create an event calendar. For inspiration, I have been referencing this example for its gallery layout and hover effects. However, I am hoping to customize thi ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

When a <a href> link is clicked, the Struts action should open as a popup

I have a form on my jsp page, <form action="test1_action" name="test" method="post" id="test"> Additionally, I have two distinct links: link1 and link2. When link1 is clicked, the form should be submitted with the action test1_action. $('#l ...

The absence of a semi-colon in JSLint

I encountered an error message indicating a semicolon is missing, however I am unsure of where to place it. Here is the snippet of code: $('.animation1').delay(350).queue(function(){ $(this).addClass("animate-from-top") }); ...