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;
You could make another css class (called apply-btn-sticky for example) that applies when a condition is satisfied:
.apply-btn-sticky {
@media {
position: sticky;
}
}
and then set the className for your button based on that condition:
<button className={this.isElementVisible ? "apply-btn" : "apply-btn apply-btn-sticky" id="calc-applyBtn">
Apply
</button>
You can reuse much of the styling from your apply-btn class since all you want to change is make the position sticky.
As answered already, you can use ternary operators. But if you already have multiple classes applied and want one class to be conditional, you can use template strings.
<div className={`btn btn-primary ${isActive ? 'active' : ' '}`}> ... </div>
you can do this with ternary operators, as you can see the below code.
<div className={!isElementVisible ? 'sticky' : 'navbar'} />