0

according to my requirement, when a user click on

<Link to="/products/shoe#product9">Go to projects and focus id 9</Link> I would like to show him the product. (hello page) for that I do this:

import React from "react";
import { Link, Route, Switch, Redirect } from "react-router-dom";
import "./products.scss";
    
const Shoes = React.lazy(() => import("./shoes/shoes.component"));
const Cloths = React.lazy(() => import("./cloths/cloths.component"));
    
function hashScroll() {
  alert("called");
  const { hash } = window.location;
  if (hash !== "") {
    setTimeout(() => {
      const id = hash.replace("#", "");
      const element = document.getElementById(id);
      if (element) element.scrollIntoView();
    }, 0);
  }
}
    
export default class Products extends React.Component {
  render() {
    return (
      <div>
        <header>
          <Link to="/products/shoe">Shoes</Link>
          <Link to="/products/cloths">Cloths</Link>
        </header>
        <h1>Products page</h1>
        <main>
          <Switch>
            <Redirect exact from="/products" to="/products/shoe" />
            <Route path="/products/shoe" onEnter={hashScroll}>
              <Shoes />
            </Route>
            <Route path="/products/cloths">
              <Cloths />
            </Route>
          </Switch>
        </main>
      </div>
    );
  }
}

I attached an onEnter function to call and scroll, so when there is a #hash let it scroll. It's not working at all. Please navigate to Hello page, from you click the link to go to products page.

Live Demo

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

2

onEnter is no longer working in react-router

What you can do is pass a prop to the component

<Shoes onEnter={hashScroll} />

inside the Shoes component execute it on componentDidMount.

componentDidMount = () => {
    if (this.props.onEnter) {
        this.props.onEnter();
    }        
};

demo

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92