Source:  Twitter logo

I want to monitor hash change and then change the state and rerender the component. so I want to know where to monitor the hash change in component lifecycle

example:

#/detail/:id  =>  #/detail

{info:[a:1,b:2]} => {info:[]}

.#/detail/:id and #/detail are the same components

If you want your component to have event listeners, you want to add those event listeners in componentDidMount, and remove the event listeners in componentWillUmount.

componentDidMount() {
    window.addEventListener("hashchange", this.doSomething, false);
}

componentWillUnmount() {
    window.removeEventListener("hashchange", this.doSomething, false);
}
19 users liked answer #0dislike answer #019
captray profile pic
captray

Use HashRouter in index.js and withRouter to get path parameters and getDerivedStateFromProps to handle the states based on the url's hash.

index.js

import ReactDOM from 'react-dom';
import { HashRouter } from "react-router-dom";

import App from './App';

ReactDOM.render(
  <HashRouter>
    <App />
  </HashRouter>,
  document.getElementById('root')
);

App.js

import { withRouter } from 'react-router-dom';

class App extends Component {

  state = { productId: null };

  static getDerivedStateFromProps(nextProps){
    const { location: { pathname } } = nextProps;       // pathname e.g.: '/detail/:8'
    const productId = pathname.split(':')[1] || null;   // ProductId: 8 OR null;
    return { productId };
  }

  ...

}

export default withRouter(App);
3 users liked answer #1dislike answer #13
gazdagergo profile pic
gazdagergo

If you want to monitor the change in route params you may do that it the lifecycle method componentWillReceiveProps

componentWillReceiveProps

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

componentWillReceiveProps: function(nextProps) {
  const {params: {id}} = nextProps;
  if(id !== this.props.params.id){
    /////////
  }
}
1 users liked answer #2dislike answer #21
Deadfish profile pic
Deadfish

For React newer version

Use window.location.hash with useEffect

useEffect( ()=> {
        doSomething();
  }, [window.location.hash])
0 users liked answer #3dislike answer #30
GMKHussain profile pic
GMKHussain

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).