Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component not re rendering on window.location change

So, I have a react component for a main menu.

Its a list of react-router <Link/> which point to different pages. Each link checks the window.location.path to figure out if it is the active page so that the active menu item can render differently.

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import List from "@material-ui/core/List";

class MainMenu extends Component {
  render() {
    return (
      <List>
        <Link to="/products" className={window.location.pathname === "/products" ? "active" : null }>Products</Link>
        <Link to="/sales" className={window.location.pathname === "/sales" ? "active" : null }>Sales</Link>
      </List>
    )
  }
}

This was actually working fine, however I now want to connect this menu component to my redux store so that I can display some data from the store inside the menu, as soon as I add the connect function the menu breaks such that when changing pages the "active" class doesn't get applied. i.e. the component does not update even though window.location.pathname has changed.

I haven't included my store code because I've tested it with dummy reducers that do nothing and also I haven't even used the data anywhere in the component yet.

export default connect(state => ({ foo: state.bar }))(MainMenu);

I'm still not sure whether this issue is to do with connect or if connect has just highlighted a problem with using window.location.pathname and react doesn't know when to update.

Any help is greatly appreciated!

like image 679
Felix Sebastian Avatar asked Mar 31 '26 16:03

Felix Sebastian


1 Answers

React component won't rerender when you change window.location.pathname. Only state changes will cause component to rerender. You need to listen to window.pathname change and map it to state then only your component will rerender

For such things you can take a look at react-router. Add it your project and such things can be easily achieved.

https://reacttraining.com/react-router/core

like image 135
Shubham Gupta Avatar answered Apr 02 '26 09:04

Shubham Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!