I have React functional component in which I have a button and I'm checking whether the button is in viewport or not, and I'm storing it as a boolean in "isElementVisible".
I want to do conditional styling here, if isElementVisible === false then I want to make it sticky else leave it as it is.
desired styling when isElementVisible === false :
.apply-btn{
margin: 0;
width: 100%;
@include media-breakpoint-up(lg) {
width: 17rem;
}
@media (max-width: 599px) {
position: fixed;
bottom: 0;
width: 50%;
text-align: center;
left: 50%;
}
}
Component:
/* eslint-disable @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access */
import React, { useEffect, useState } from 'react';
const CalcOutput = (): JSX.Element => {
const [isElementVisible, setIsElementVisible] = useState(false);
const applyNowButton = document.getElementById('calc-applyNowBtn');
const isElementInViewPort = (element: HTMLElement) => {
const rect = element.getBoundingClientRect();
return(
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
const handleScroll = (event: Event) => {
if(applyNowButton !== null) {
const isVisible = isElementInViewPort(applyNowButton)
isVisible ? setIsElementVisible(true) : setIsElementVisible(false);
}
};
window.addEventListener('scroll', handleScroll);
return (
<button className="apply-btn" id="calc-applyBtn">
Apply
</button>
);
};
export default CalcOutput;