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

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...

Utilizing doT.js for Organizing Nested Lists from Arrays and Objects

Can nested lists be generated with doT.js? My current code only processes the first object in the array (g1) and ignores the rest. Is there a solution for this using doT.js? The desired result should be: G1 T11 T12 T13 G2 T21 T22 T23 $(document) ...

What kind of interference occurs between the sibling components when a div with ng-if is present in Angular?

I've been troubleshooting for hours to figure out why the Angular elements in one div suddenly stopped working. After some investigation, I realized that a sibling div with an ng-if="someVar" was causing the issue. Currently, when someVar is true, the ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Is it possible to incorporate AngularJS 1.4, AngularJS 2.0, and ReactJS all within the same project?

My project is a collection of tags that are referred to by different names in various languages. I refer to these elements as views. Currently, our users are creating views using Angular 1.4. I am looking to provide flexibility to our users so they can ...

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

The image stored in the express static folder is not loading properly for the user

I am currently working on a Node.js app that is served by express, with the frontend developed using React.js. However, I am facing an issue where my static folder containing images seems to be unreachable on the client side. When trying to access the ima ...

Modifying the border hue of Material-UI's Select Component

Here is the Select component I've created using materials-UI <FormControl variant="outlined"> <Select value={this.state.value} onChange = {this.handleChange} className={this.props.classes.select} inputProps = {{class ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggested to t ...

Issue with displaying ng-repeat data in AngularJS tbody

I am experiencing an issue with using ng-repeat inside a tbody element. Here is the code snippet that is causing trouble: <tbody> <tr ng-repeat="group in groups"> <td>{{ group.name }}</td> </tr> </tbody> Wh ...

Obtaining the width of a child table using Jquery

I have a question that might seem simple, but I can't figure it out. How can I use jQuery to get the width of a table that is a child of a div with the class "test"? <div class="test"> <div id="one"> </div> <table> <thead&g ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

Creating a structure object in a Laravel controller for implementing Vue.js autocomplete functionality

I am currently facing an issue with my autocomplete feature not displaying options correctly. To start off, I am fetching hard coded data from my controller and passing it through an axios call: searchController.php $searchResults = [ 0 => (ob ...

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...

What could be the reason behind my Javascript code returning "object object"?

I am a beginner with jQuery. I attempted to calculate the sum of items from my django views using jQuery. Here's what I have so far: $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); ...

Determine the closest input value by clicking a specific link

Can you help me with a task involving text inputs and links? <p><input type="text" name="color[]" value="orange" /> <a href="#" class="show-color">color</a><br /> <input type="text" name="color[]" value="purple" /> < ...