While I have a pretty good understanding of React, I am still quite fresh to it and
learning it patiently every day.
Today I needed to use the Intersection Observer to change the background of the navbar in the project I am
working on now. Or at least, Intersection Observer is what I thought I needed and what I would use with
Vanilla JavaScript.
I chose to go for an initially transparent navbar background that would transition to a coloured background
when we start scrolling.
After I learned how to use Intersecition Observer in React, I found this super easy solution which doesn't involve using it at all!
First, we need to import useState.
import { useState } from "react";
Then we need to declare our useState inside of our component and write a function that would change the state of our color from false to true.
const [color, setColor] = useState(false)
const changeNavbar = () => {
if (window.scrollY >= 100) {
setColor(true)
} else {
setColor(false)
}
}
window.addEventListener('scroll', changeNavbar)
Now, in our .css styles file let's create a class that will add a colour to the transparent background of our navbar.
.navbar-dark {
background-color: #333333;
}
Finally, let's use the ternary operator to dynamically assign a class to our chosen DOM element. For this example I chose header. If we scroll and the state of color changes to true, the header (that already has one class "header") will get "navbar-dark" class. If state of color is false the header will not receive this class and stay transparent.
<header className={color ? 'header navbar-dark' : 'header'}>
And that's it! Very straightforward and super quick.
Comments (0)
Be the first to leave a comment