Navigating React Router: Updating the page on back button press

Looking for a solution to a persistent issue. Despite various attempts and exhaustive research, the problem remains unresolved.

Here's the situation: Within my React-Router-Dom setup, there is a parent component featuring a logo that remains fixed and visible across all child components/pages.

class Parent extends React.Component {
  render() {
    return (
       <div>
        {window.location.pathname==='/contact' ? 
         null :
         <div className='originalLogo'></div>
        }
       </div>

) } }

On the contact page, a modified version of the logo is displayed, while the original logo is set to null.

class Child extends React.Component {
   render() {
     return (
      <div className='modifiedLogo'></div>
  )

} }

The issue arises when a user navigates back from the contact page using the browser's back button. When returning to the homepage in this manner, the logo reverts to the original version. However, if the user returns to the homepage via the menu, the logo remains in its modified state until a menu item is clicked to trigger a re-render.

How can I automatically trigger a re-render when the user goes back using the browser's back button?

Answer №1

To solve the issue, you can utilize the Switch and Route components in your React application. These components not only allow you to render entire pages but also specific parts of a page.

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

class Parent extends React.Component {
    render() {
        return (
            <Switch>
                <Route path="/contact" render={() => null} />
                <Route render={() => <div className='originalLogo' />} />
            </Switch>
        );
    }
}

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

Having difficulty extracting images from a collection - web scraping struggle

I have a basic understanding of web scraping but I am facing an issue. I am using PHP Simple HTML DOM and struggling to extract images from within each 'li' tag. <ul class="slides"> <li> <img src="www.webpage.com/oH7oCOEhQAB ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

There has been an internal server error: TypeError occurred due to the inability to convert undefined or

I'm working on implementing signIn functionality using nextauth.js. Below is the code snippet I am using: import { getProviders, signIn as SignIntoProvider } from 'next-auth/react' import Header from '../../Components/Header' ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

Ensuring JSON data protection when sending Ajax requests in JavaScript (for(;;);)

After extensive research, I have not been able to find the answer I'm looking for despite similar questions being asked. My query concerns the usage of for(;;); while(1); before an Ajax response outputs a JSON string. I am curious about how this tec ...

jQuery UI - Inconsistent results with multiple autocomplete feature

I am facing an issue with the tags.json file provided below: [ {"label" : "Aragorn"}, {"label" : "Arwen"}, {"label" : "Bilbo Baggins"}, {"label" : "Boromir"} ] In addition, I have a JavaScript code snippet (which ...

Why did the CSS rendering suddenly come to a halt?

I am facing a confusion with EJS. When I make a post request, EJS renders my CSS properly. However, when I try the following code snippet: exports.resetpassword = async (req, res) => { const {id, token} = req.params; const user = await LoginMo ...

Android not showing scroll bar in ion-scroll feature

I am experiencing an issue where a div with a fixed height displays a scroll bar on browsers but not on an Android phone. <ion-scroll style="height:300px;" scrollbar-y='true'> //content </ion-scroll> ...

Exploring the intricacies of AngularJS: Unraveling the

I’m currently diving into the world of Angular and grappling with retrieving JSON data. However, the concepts of $scope and $http are still a bit fuzzy for me. Can someone provide a clear explanation of what $scope and $http mean in this context? Below ...

Issue persists with Angular 2 *ngFor functionality even after successfully importing CommonModule

After creating a feature module using the CLI, I imported the common module as shown below: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home/home.compo ...

"Can you guide me on how to add a background pattern image to an HTML tooltip arrow

I've been working on a customized jQuery plugin for tooltips. The tooltip box appears when the mouse hovers over a specific element, complete with an arrow pointing towards the base element. My goal is to apply a repeating texture image to the entire ...

Utilize a function within an AngularJS directive

I'm struggling to understand how to pass a function (delegate) to a directive in AngularJS and utilize it within the link-function. Any guidance or suggestions on the correct approach would be immensely appreciated. Below is the controller code: myA ...

Strategies for transferring data between controllers and configuration files in AngularJS

I'm attempting to pass a variable to the angular js config, Here is my JavaScript app: var app = angular.module('myApp', ['ngMaterial', 'sasrio.angular-material-sidenav', 'ui.router']); app.controller('ba ...

repeating timer modifying state within the component

Question: I have an interval set up in my component: componentDidMount(){ this.timeID=setInterval(()=>{ this.setState({ text:this.props.text+"." }) console.log(this.state.text); },1000) However, currently it only adds one dot to the text e ...

execute numerous Jssor Caption instances simultaneously

I have a Jssor slider and I want to create an animation for the first slide. My goal is to make two images come from the sides and merge in the center. I tried using a div for each image with a caption, and it works well. However, the second image starts ...

What could be the reason for the modal-side modal-top-right class not functioning properly in Bootstrap modals

Here is the code snippet: <div class="modal fade right" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-side modal-bottom-right"> <div class="modal-content"&g ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Design a dynamic card with an eye-catching Font Awesome icon that adapts well to

As I delve into the realm of CSS, my current mission is to replicate the captivating cards showcased on this particular website. Utilizing Font Awesome icons has become a pivotal aspect of this endeavor. For instance, let's take a look at this card:ht ...

Arrangement of multiple boxes in a single row using HTML code

Struggling to solve this supposedly simple problem, I'm reaching out for help. I need assistance in arranging multiple inputs with corresponding labels, all stacked horizontally on a single line as shown in the image. ...

Is there a way to style the nav-item element specifically on the current page I'm viewing?

I'm just starting out with Vue.js and Nuxt and I need some guidance on how to apply a background image (blue line at the top of items) only to my active page (such as the contact page). https://i.sstatic.net/maDzc.png This is the HTML code I am usin ...