Modify Navbar Color based on State using Styled Components

I am looking to update the navbar color upon scrolling using the useState hook.

const Navbar = () => {

    const [colorChange, setColorchange] = useState(false);

    const changeNavbarColor = () =>{
       if(window.scrollY >= 38){
         setColorchange(true);
       }
       else{
         setColorchange(false);
       }
    };

    console.log(setColorchange)

    window.addEventListener('scroll', changeNavbarColor);

I need help figuring out how to control the background property of the styled component below using state.

const NavbarContainer = styled.div`
    width: 100%;
    height: 38px;
    background-color: red;
    margin-top: 10px;

    display: flex;
    justify-content: space-between;
    position: sticky;
    top:0;
    z-index: 1;
`;

Answer №1

Passing props is a useful feature:


<HeaderWrapper background={selectedColor}>
 ...
</HeaderWrapper>

const HeaderWrapper = styled.div`
    background-color: ${props => props.background};
    // Feel free to include dynamic javascript logic, such as:
    color: ${({background}) => background === 'light' ? 'black' : 'white'}
`;

Answer №2

const HeaderBar = styled.div`
    width: 100%;
    height: 36px;
    background-color: ${props => props.colorChange ? "green" : "yellow"};
    margin-top: 12px;

    display: flex;
    justify-content: space-around;
    position: fixed;
    top:0;
    z-index: 2;
`;

Answer №3

In my opinion, a great approach is to dynamically update the className of your component based on its current state. Additionally, it's important to initialize your event listener within the useEffect hook and remove it when the component is unmounted.

import React, { useEffect, useState } from 'react';

const Navbar = () => {
    const [colorChange, setColorchange] = useState(false);

    const changeNavbarColor = () => {
       if(window.scrollY >= 38){
         setColorchange(true);
       }
       else{
         setColorchange(false);
       }
    };

    useEffect(() => {
        window.addEventListener('scroll', changeNavbarColor);
        return () => {
            window.removeEventListener('scroll', changeNavbarColor);
        }
    }, [])
    
    return (
        <div className={colorChange ? 'colorBlack' : 'colorWhite'}>
            <p>Your navbar</p>
        </div>
    )
}

export default Navbar;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Workbox background sync - Retrieving replayed API responses

Currently, I am utilizing the Workbox GenerateSW plugin and implementing the backgroundSync option within runtimeCaching. You can find more information in the documentation here. This powerful plugin enables me to monitor APIs and successfully retry faile ...

Tips for mastering the PrimeFaces JavaScript API

While exploring JSF-2.2 in conjunction with PrimeFaces 5.3, I encountered JavaScript event handlers like the one utilized with the onComplete attribute: function handleSmptmSaveRequest(xhr, status, args) { if (args.validationFailed) { PF(&apos ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...

What steps can be taken to allow for the addition of multiple slick sliders using the same class on a single page?

When using the admin panel, the user has the ability to add multiple sliders to the page. How can all sliders with the same class be initialized? Is there a way to ensure that the control buttons for each slider are applied individually, instead of just f ...

Efficient Ways to Present and Personalize Indian Date and Time using JavaScript

Hey there, currently creating my website and need some assistance. I'm looking to display the date and time in different sections of the page. Having some trouble with getting Indian time to work properly using PHP. If you could help me out with Ja ...

The scrolling element mirrors the movement of the scrolling window

Can you help me understand how to create a scrolling element that follows the scrolling of the window? I want the element to scroll down when the window reaches the end, and scroll up when the window is at the top. I tried implementing this functionality ...

Exploring the elements within array structures

I'm facing an issue with my API response. I'm trying to filter the links and check if the source and target name properties in each object match a specific string. However, I am having trouble accessing the name property. Any suggestions on how I ...

What is the method for overlaying an image and having it expand to fit the parent container using flexbox?

I'm working on styling an HTML element where I want the txt-box div to be centered within its container, overlaying an image while expanding to fill the container. The goal is for it to have a margin of equal width on all sides, creating a border-like ...

The like count displayed in Django's AJAX feature is identical for every post

Having an issue with the ajax setup in my django twitter clone app. Every post's like count remains the same after clicking the like button, but it gets updated after a page refresh. I'm close to fixing it, but currently stuck. View: def add_li ...

Error displayed inline

I am facing an issue with a hidden textbox that I need to make visible based on a certain condition. Despite checking that the control is being triggered by the change event, I am unable to get it to display. I have experimented with different methods with ...

The animation function occasionally halts unexpectedly at a varying position

I am facing an issue with an animation function that I have created to animate a list of images. The function takes in parameters such as frames per second, the stopping point, and the list element containing all the images. However, the animation stops un ...

Struggling with Conditional rendering in React JS - Need help!

I am currently working on a web application that fetches product/data from a backend API and displays it on the frontend. I am also implementing an 'add to cart' and 'remove from cart' functionality. My goal is to display 'add to c ...

Using footable js will eliminate all form elements within the table

After incorporating the Footable jQuery library to create a responsive table, I encountered an issue with input tags and select boxes being removed by the Footable JavaScript. It turns all these tags into empty <td> elements. <table id="accordi ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Display and conceal information upon tweeting

Can anyone help me troubleshoot an issue with hiding the Twitter button after displaying new content? I tried adding a script to make it work, but it's still not functioning properly. Any insights on what I might be doing wrong would be greatly apprec ...

Designing scroll boxes that are not continuous and tracking the time spent in each section

I'm seeking assistance with a unique challenge involving the creation of scroll boxes for use in a Qualtrics survey and tracking the time spent viewing different sections of text within them. Specifically, I aim to design a scroll box featuring two p ...

Attempting to implement a Material UI dialog within a specialized contextual modal

I am experiencing an issue with my modal component that I have placed in a context. When I return html, including some divs, there are no issues. However, I would prefer to use the material-ui dialog for this purpose. Unfortunately, when I try to implemen ...

Typescript throws an error indicating that the "this" object in Vue methods may be undefined, displaying error code TS2532

As a beginner in question writing, I apologize if my wording is not clear. The issue at hand: I am working on a Vue application with TypeScript. export default { methods: { setProgram: (program: Program)=>{ this.program = progra ...