I am trying to change the url while scrolling the page.
I am using jQuery .scroll() for that. The problem is that this
on $(this)
grabs the context of the React component. How can I change this code to make it work?
import React from 'react';
import $ from 'jquery';
class Main extends React.Component {
componentDidMount() {
$(() => {
let currentId = 'about';
$(document).scroll(() => {
$('.path').each(() => {
const top = window.pageYOffset;
const distance = top - $(this).offset().top;
const path = $(this).attr('id');
if (distance < 50 && distance > -50 && currentId !== path) {
window.history.pushState(null, null, '/' + path);
currentId = path;
}
});
});
});
}
render() {
return (
<main role="main">
<About />
<Contact />
</main>
);
}
}
export default Main;
Just as a complement, I am following these 'helpers' and adapt them to my needs:
The accepted answer for this question: Change url when manually scrolled to an anchor?
This jsfiddle: jsfiddle