Skip to content

Commit

Permalink
refactoring ScrollButton using hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
danretegan committed Feb 15, 2024
1 parent 7e9e778 commit 1ff705f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 32 deletions.
62 changes: 30 additions & 32 deletions src/components/scrollButton/ScrollButton.jsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,43 @@
import React, { Component } from 'react';
import React, { useEffect, useState } from 'react';
import styles from './ScrollButton.module.css';

class ScrollButton extends Component {
componentDidMount() {
window.addEventListener('scroll', this.scrollFunction);
}
const ScrollButton = () => {
const [displayButton, setDisplayButton] = useState(false);

componentWillUnmount() {
window.removeEventListener('scroll', this.scrollFunction);
}
useEffect(() => {
const handleScroll = () => {
if (window.scrollY > 20) {
setDisplayButton(true);
} else {
setDisplayButton(false);
}
};

scrollFunction = () => {
const mybutton = document.getElementById('btn-back-to-top');
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
) {
mybutton.style.display = 'block';
} else {
mybutton.style.display = 'none';
}
};
window.addEventListener('scroll', handleScroll);

return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);

backToTop = () => {
const backToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};

render() {
return (
<button
id="btn-back-to-top"
className={styles.ScrollButton}
onClick={this.backToTop}
>
Scroll to Top
</button>
);
}
}
return (
<button
id="btn-back-to-top"
className={`${styles.ScrollButton} ${
displayButton ? styles.show : styles.hide
}`}
onClick={backToTop}
>
Scroll to Top
</button>
);
};

export default ScrollButton;
8 changes: 8 additions & 0 deletions src/components/scrollButton/ScrollButton.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,11 @@
.ScrollButton:active {
transform: scale(0.95);
}

.show {
display: block;
}

.hide {
display: none;
}

0 comments on commit 1ff705f

Please sign in to comment.