2

My React component is as follows :

var ContentBox = React.createClass({

  componentDidMount:function() {
    this.getContents();
  },

  getContents:function() {
    $.ajax({
      url : ......
      success:function(contents) {
        this.setState({
          contents : contents
        });
      }.bind(this)
    });
  },

  componentDidUpdate:function() {
    ReactDOM.findDOMNode(this).scrollTop = 0;
  }
});

Essentially, what I'm trying to do is that when the page is rendered, I want to scroll to the top of the page. The "contents" change depending on the route parameters.

I've tried the solution given in Scroll to the top of the page after render in react.js But it's not working on mine.

UPDATE : The following worked

  componentDidUpdate:function() {
    ReactDOM.findDOMNode(this).scrollIntoView();
  }

Why doesn't ReactDOM.findDOMNode(this).scrollTop = 0; work? Also, I've tried $(window).scrollTop() but that also doesn't work. I tried to put them in the "success" function of the AJAX request, but that doesn't work either.

Community
  • 1
  • 1
ericbae
  • 9,604
  • 25
  • 75
  • 108

1 Answers1

0

For react-router-dom v6+

  1. Open App.js file and import:
import { Route, Routes, useLocation } from "react-router-dom";
import { useLayoutEffect } from "react";
  1. Create a scrollTop function just above the "App" function:
const scrollTop = ({ children }) => {
  const location = useLocation();
  useLayoutEffect(() => {
    document.documentElement.scrollTo(0, 0);
  }, [location.pathname]);
  return children;
};
  1. Wrap your routes within the scrollTop function:
function App() {
  return (
    <div className="App">
      <scrollTop>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/service" element={<Service />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </scrollTop>
    </div>
  );
}

Here is the completed code

// Import all the pages (Home, about, service, contact)

import { Route, Routes, useLocation } from "react-router-dom";
import { useLayoutEffect } from "react";

const scrollTop = ({ children }) => {
  const location = useLocation();
  useLayoutEffect(() => {
    document.documentElement.scrollTo(0, 0);
  }, [location.pathname]);
  return children;
};

function App() {
  return (
    <div className="App">
      <scrollTop>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/service" element={<Service />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </scrollTop>
    </div>
  );
}

export default App;