-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
60 lines (57 loc) · 1.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require('smoothscroll-polyfill').polyfill();
import React from 'react';
import PropTypes from 'prop-types';
const Element = (props) => { return ( props.children ); };
class Scroll extends React.Component {
static propTypes = {
type: PropTypes.string,
element: PropTypes.string,
offset: PropTypes.number,
timeout: PropTypes.number,
children: PropTypes.node.isRequired
}
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
let elem = 0;
let scroll = true;
const { type, element, offset, timeout } = this.props;
if (type && element) {
switch (type) {
case 'class':
elem = document.getElementsByClassName(element)[0];
scroll = elem ? true : false;
break;
case 'id':
elem = document.getElementById(element);
scroll = elem ? true : false;
break;
default:
}
}
scroll ? ( this.scrollTo(elem, offset, timeout) ) : console.log(`Element not found: ${element}`); // eslint-disable-line
}
scrollTo(element, offSet = 0, timeout = null) {
const elemPos = element ? element.getBoundingClientRect().top + window.pageYOffset : 0;
if (timeout) {
setTimeout(() => { window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' }); }, timeout);
} else {
window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' });
}
}
render() {
return (
<Element>
{typeof(this.props.children) === 'object' ? (
React.cloneElement(this.props.children, { onClick: this.handleClick })
) : (
<span onClick={this.handleClick}>{this.props.children}</span>
)}
</Element>
);
}
}
export default Scroll;