nerdess
nerdess

Reputation: 10920

trigger react-router after document is ready in react.js

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 :)

Upvotes: 0

Views: 1125

Answers (1)

Tyler McGinnis
Tyler McGinnis

Reputation: 35276

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.

Upvotes: 1

Related Questions