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 a onEnter function to call and scroll. so when there is a #hash let it scroll. but it's not works at all. any one help me? please navigate to Hello page, from you click the link to go to products page.

Live Demo

3gwebtrain
  • 13,401
  • 21
  • 93
  • 195

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
  • 20,702
  • 5
  • 63
  • 84