0

i am using react-router 4.0 and the routing depends on the positioning of certain elements within the DOM. this works fine unless the user goes directly to localhost/apple or localhost/pear. this is because the routing wants to do its magic before the DOM has loaded.

how can i trigger the routing after the DOM has loaded?

here is my code:

import React, { Component } from 'react'
import './App.css'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

var Scroll = require('react-scroll')  

const Child = ({ match }) => (
<div>
{     Scroll.animateScroll.scrollTo(document.getElementById(match.params.id).getBoundingClientRect().top)
}
</div>
)

class App extends Component {
render() {
return (
  <div>
    <Router>
      <div>
        <h2>Demo</h2>
        <ul>
          <li><Link to="/apple">Apple</Link></li>
          <li><Link to="/pear">Pear</Link></li>
        </ul>
        <Route path="/:id" component={Child}/>
      </div>
    </Router>

    <div id="apple" style={{backgroundColor: 'red', height: '100vh'}}>
    Apple
    </div>

    <div id="pear" style={{backgroundColor: 'blue', height: '100vh'}}>
    Pear
    </div>

    </div>

   );
  }

}

export default App;

ps: i am just making my first baby steps with react so please be nice :)

1
  • Could you use the componentDidMount lifecycle method (you'll have to use a full class instead of a stateless function) to trigger the scrolling? Commented Mar 16, 2017 at 21:21

1 Answer 1

1

You shouldn't be doing scrollTo stuff inside of your render function. That's what componentDidMount is for. Try this code,

class Child extends React.component {
  componentDidMount () {
    return Scroll.animateScroll.scrollTo(document.getElementById(this.props.match.params.id).getBoundingClientRect().top)
  }
  render () {
    return null
  }
}

With that said, I don't really think you need React Router for this as you're just scrolling on the same page.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot, this was the nudge i needed, already understanding react a bit better now :) used componentWillReceiveProps() if the user clicks on a link and compenendDidMount() if the user goes to a path directly via the url. btw: i think i do need react router because i want the links to look like proper url's in the browser and not just be anchors.
sorry i meant componentDidUpdate() instead of componentWillReceiveProps()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.