What is the best way to alter the background-color of an element that is contained within a GatsbyJS component, depending on the specific page where the component is being utilized?

As a first-time GatsbyJS website builder, I am working on creating reusable components for my site. One of these components is the footer, and I have already structured it. Now, I have a dilemma - I want to change the color of a specific <div> within the footer based on the page being visited.

Specifically, I want this div to have an orange background when visiting the Homepage and a blue background when on the contact page. Is this even possible?

Here's a snippet of the code for my footer (which is the footer.js Gatsby component that I import into my pages):

<footer className={footerStyle.footer}>
  <div className={footerStyle.parteSopra}>
    <div className={footerStyle.parteSopra}>
      <div className={footerStyle.ottanta}>
        <h3 className={footerStyle.rimaniamo+ ' '+footerStyle.dimTitoli}>rimaniamo<br />in contatto</h3>
      </div>
      <div className={footerStyle.venti}>

      </div>
    </div>
    <div className={footerStyle.parteSotto}>
      <div className={footerStyle.ottanta+ ' '+footerStyle.boxFrecciaBlu}>
        <div className={footerStyle.contieniFrecciaBlu}>
          <img className={footerStyle.frecciaBlu} src={frecciaBlu} alt="Freccia giù" />
        </div>
      </div>
      <div className={footerStyle.venti+ ' '+footerStyle.boxFbEInstaBlu}>
        <div className={footerStyle.contieniFbBlu}>
          <a href="https://it-it.facebook.com/DiamanteCalzature" target="_blank" rel="noopener noreferrer">
            <img className={footerStyle.fbBlu} src={iconaFbBlu} alt="Facebook" />
          </a>
        </div>
        <div className={footerStyle.contieniInstaBlu}>
          <a href="https://instagram.com/diamantecalzature?igshid=cta3uh8iob7a" target="_blank" rel="noopener noreferrer">
            <img className={footerStyle.instaBlu} src={iconaInstaBlu} alt="Instagram" />
          </a>
        </div>
      </div>
    </div>
  </div>
  <div id="coloreFootSotto" className={footerStyle.parteSotto+ ' '+footerStyle.coloreFooterSotto}>
    <div className={footerStyle.ottanta}>

    </div>
    <div className={footerStyle.venti+ ' '+footerStyle.boxTornaSu}>

    </div>
  </div>
</footer>

When importing this into my pages with <Footer />, I thought about adding an attribute or prop to dynamically change the background-color of the div with Id id="coloreFootSotto" depending on the visited page. Currently, I'm manually manipulating the DOM in some pages to achieve this effect, but I wonder if there's a way to do it using props or similar methods.

Is anyone familiar with how to accomplish this? Thank you!

Answer №1

Gatsby utilizes reach router which allows you to utilize useLocation in your component and manipulate the location.pathname for specific routes.

// Footer.js
import React from 'react';
import { useLocation } from "@reach/router"

import Container from 'components/Container';

const Footer = () => {
  const {pathname} = useLocation()
  console.log(pathname)
  return (
    <footer style={pathname=== '/' ? {backgroundColor: 'blue'} : null} >
      <Container>
        <p>&copy; {new Date().getFullYear()}, My Gatsby Site</p>
      </Container>
    </footer>
  );
};

export default Footer;

It's important to note that you can access location data from a gatsby page through its location prop.

Depending on your app structure, you may also retrieve this data from your page component and pass it down via props through your component tree.

For example: IndexPage > Layout > Footer

For multiple pages, consider implementing something like the following.

// Footer.js
import React from 'react';
import { useLocation } from "@reach/router"
import Container from 'components/Container';

const pagesWithColoredFooter = ['/', '/page-2', 'page-3'];

const Footer = () => {
  const {pathname} = useLocation()
  console.log(pathname)
  return (
    <footer style={pagesWithColoredFooter.includes(pathname) ? {backgroundColor: 'blue'} : null} >
      <Container>
        <p>&copy; {new Date().getFullYear()}, My Gatsby Site</p>
      </Container>
    </footer>
  );
};

export default Footer;

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

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

Changing the value of one particular key within an object during a reduce operation will impact all other keys within the object as well

I'm completely lost here. It seems like there's a reference issue causing all data properties to be overwritten with the value of the last row. I need help figuring out how to iterate over a list of objects, using specific keys to assign data to ...

What is the best way to direct the next input focus when pressing Enter in ReactJS?

I have a TextField component from MaterialUI in my ReactJS project. I want to set focus on the next field when the enter key is pressed on a Google Keyboard. Can anyone guide me on how to achieve this functionality? ...

Unable to alter the protocol option of the request object in SailsJS

Currently, I am utilizing a library that relies on the req.secure option to proceed without any errors. However, my application is deployed on Heroku and I have implemented custom middleware to check the "x-forwarded-proto" header and set req.secure as tru ...

Struggling to create a flawless gradient fade transition

Looking to create a gradient overlay on my images for a specific effect: The goal is to have the gradient darker at the bottom, while leaving the top unaffected by the darkness. I attempted the following code: @include linear-gradient(to top, rgba(0,0,0 ...

Utilizing MUI and Next.js 13, we can take advantage of MenuItem and NextLink to manipulate padding and height in order to ensure that the anchor element matches the

The "HTML":  <MenuItem> <NextLink className={currentRoute == "/") ? "link--is-active" : ""} href={"/"}> HOME </NextLink> </MenuItem> When clicking outside the anchor in the nav link, you get a nice MUI effect, but the URL ...

Retrieving user input through JavaScript and transmitting information using Ajax

UPDATE: Issue resolved by changing name="demo_name" and similar attributes on my form to id="demo_name". Thanks @Jill I'm attempting to save contact form data into a MySQL database using jquery's ajax feature. I'm new to this, and while it& ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

Tips for showcasing content on a jQuery calendar

I have a jQuery calendar implemented on my website and I would like to show a list of local holidays on the calendar. The calendar is functioning correctly with the script below, but I just need help displaying the holidays. <script> $(document).r ...

Arrange the Elements of Select Options

I am currently facing an issue with organizing the elements in my select list. I have two interconnected lists, one containing a list of "models" which I have successfully sorted using the following function: var sel = $('#model'); var opts_lis ...

Implementing a loading animation effect using AJAX that requires a loop delay and sleep functionality

My jquery ui dialog is loaded via ajax with a partial view from the server. Initially, the dialog opens as a dialog-ajax-loader and then animates/grows to fit the content once the call returns. The issue arises when the dialog content gets cached or the a ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...

Whenever I attempt to import varied liveries, I consistently encounter the same errors

I experimented with webdriverio, puppeteer, playwright, and bowser but encountered the same issues when using React. All I did was $ yarn add webdriverio (or another) and then import { remote } from 'webdriverio'; or const playwright = requi ...

Testing the equality of nested arrays: A step-by-step guide

My maze generator creates walls for each "cell", resulting in duplicate walls - such as the left wall of one cell being identical to the right wall of the adjacent cell. I have managed to convert the maze data into a different program where it is stored in ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...