Skip to content

Instantly share code, notes, and snippets.

@a-m-dev
Last active July 10, 2018 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-m-dev/7c3045bfbe09b24ff3dc23d4cc3bf7e3 to your computer and use it in GitHub Desktop.
Save a-m-dev/7c3045bfbe09b24ff3dc23d4cc3bf7e3 to your computer and use it in GitHub Desktop.
scroll top in react using ReactDOM
import React from 'react'
import ReactDOM from 'react-dom'
import AroundIcons from './AroundIcons'
class ResumeComponent extends React.Component {
constructor(props) {
super();
this.state = {
elementOffsetTop: 10000, // setting this to a large number as initial scroll offset
wScroll: 0,
wInnerHeight: ''
}
// bindings
this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount() {
window.addEventListener('scroll' , this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll' , this.handleScroll);
}
handleScroll(e) {
// getting elemtn distance from its position to top
// let elementOffsetTop = parseInt(ReactDOM.findDOMNode(this).getBoundingClientRect().top); // INSTEAD OF THIS USE BELOW
let elementOffsetTop = parseInt(ReactDOM.findDOMNode(this).offsetTop) //.getBoundingClientRect().top);
// getting value of how much we scrolled down
let wScroll = window.scrollY;
let wInnerHeight = window.innerHeight;
// setting the values to state of class
this.setState({
elementOffsetTop: elementOffsetTop,
wScroll: wScroll,
wInnerHeight: wInnerHeight
})
}
render() {
const { id, type , company , begin_to_work, end_of_work , decription } = this.props.data
const classname = `resume ${type.toLowerCase()}`
console.log( type + ' => ' + this.state.elementOffsetTop);
console.log( '*****WSCROLL*****' + ' => ' + this.state.wScroll);
const { elementOffsetTop , wScroll , wInnerHeight } = this.state
// const coloredClass = wScroll > elementOffsetTop * 3.5 ? '-enabled' : ''; // INSTEAD OF THIS USE BELOW
const enabled = wScroll > elementOffsetTop - (wInnerHeight / 4)*3 ? '-enabled' : '';
return(
<div className={classname}>
<div className='header'><span>{company}</span></div>
<p>{decription}</p>
<div className='duration'><span>{`${begin_to_work} - ${end_of_work}`}</span></div>
<AroundIcons type={type} classname={enabled} />
</div>
)
}
}
export default ResumeComponent;
@a-m-dev
Copy link
Author

a-m-dev commented Jul 10, 2018

@a-m-dev
Copy link
Author

a-m-dev commented Jul 10, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment