Utilize Styled Components in React.js to target precise classes

Struggling with integrating a theme into a navbar component that includes a sticky effect on scroll. The issue arises when trying to target the 'sticky' class using styled-components instead of regular CSS. Any ideas on how to properly target the className 'sticky'? Thanks in advance!

    export function Nav() {
      const [theme, setTheme] = useState("light");
      const [theTheme, setTheTheme] = useGlobal("onTheme");

      useEffect(() => {
        if (theTheme == false) setTheme("dark");
        else setTheme("light");

   
        window.addEventListener("scroll", function () {
        var header = document.querySelector("header");
        header.classList.toggle("sticky", window.scrollY > 0);
    });
  });

  return (
    <ThemeProvider theme={getTheme(theme)}>
      <Head>
        <Navbar>
          <NavLink></NavLink>
          <NavItem icon={<CaretIcon />}>
            <DropdownMenu />
          </NavItem>
        </Navbar>
      </Head>
    </ThemeProvider>
  );
}

The 'sticky' class can be targeted with normal CSS.

    header.sticky {
      background-color: rgb(31, 31, 37);
    }

Now attempting to target 'sticky' using Styled Components.

    export const Head = styled.header`
      position: fixed;
      width: 100%;
      background-color: transparent;
      top: 0rem;
      transition: 0.6s;
      z-index: 100000;
      text-decoration: none;
      & .sticky {
        background-color: ${(props) => props.theme.hoverColor};
       } 
     `;

Answer №1

It appears that a single unnecessary space between & .sticky is causing the styles to apply to children elements instead of the header itself. The corrected version should look like this:

export const Head = styled.header`
  position: fixed;
  width: 100%;
  background-color: transparent;
  top: 0rem;
  transition: 0.6s;
  z-index: 100000;
  text-decoration: none;

  &.sticky {
     background-color: ${(props) => props.theme.hoverColor};
  } 
`;

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

utilizing React.js, learn how to extract the most recent user input and store it within an array

My Input component generates input tags dynamically based on JSON data. I've implemented the onChange method in the input tag, which triggers a function called "handleChange" using contextAPI to record the values in another component. The issue aris ...

Alter the background color of a div contingent on the checkbox being checked within

I am in search of a solution to modify the background color of a parent div that contains a checkbox. The condition is that the background color should only change when the 'checked' attribute is present within the tag. HTML <div class="comp ...

What is the best way to retrieve all classes that have a hyphen/dash in them from a DOM element and then store them in an array using JavaScript?

How can I retrieve all classes that contain a hyphen/dash applied to any DOM element and store them in an array using JavaScript? My current approach: const getClasses = []; const classesContain = []; document.querySelectorAll('*').forEach( ...

Most efficient method for dynamically changing HTML content with JavaScript

Can anyone provide guidance on how to switch HTML content using JavaScript? For example: if($sid == 0) {insert one HTML code} else {insert another HTML code} Which method is preferable - LESS, jQuery, CSS3, etc? ...

Is there a way to enable scrolling on a page without editing the HTML? I have a table inside a div that is overflowing, and I want the page to scroll,

I'm facing an issue with a DIV that is 600px wide and contains a table. Due to long email addresses, the wrapping isn't working properly even after using word-wrap: break-word. I've experimented with changing the width, adding !important, a ...

Discovering the properties in an object using a variable name in JavaScript

I am sending my string to the function below. $scope.sort= function(query){ console.log(query); // returns "name"; $scope.resultset.sort(function(a, b) { return parseFloat(b.query) - parseFloat(a.query); //returns undefined; }); }; wher ...

glsify - encountering the error message 'This file type could require a specific loader to be handled'?

Currently, I'm attempting to implement a custom shader following the guidance provided at https://tympanus.net/codrops/2019/01/17/interactive-particles-with-three-js/. I have imported the .frag and .vert files (provided in the link) and replicated the ...

Develop a Vue.js component embedded within another component to manipulate data stored in the parent

After reviewing a few answers that partially address my question, I realized there is more to explain. In our Laravel project website layout, we utilize a global #app div. This means all pages share the same main Vue instance, prompting me to segregate ke ...

Discovering the Maximum Value in a PostgreSQL Column

If there was a database table that kept track of the test scores of students. CREATE TABLE scores ( student_id SERIAL PRIMARY KEY, name VARCHAR(100), test1 INTEGER, test2 INTEGER, test3 INTEGER, test4 INTEGER, highest_score VARCHAR(50) ) How could I calc ...

Ways to ensure the bootstrap table header width aligns perfectly with the body width

I am having an issue with my bootstrap table where the header width is smaller than the body width because I set the table width to auto. How can I align the header and body widths? Here is a link to a plunker showcasing the problem. https://plnkr.co/edit ...

jquery unbinding events can lead to faster performance

I'm in the process of creating a content-heavy slideshow page that heavily relies on event triggers, with about half of them utilizing the livequery plugin. I'm curious if unloading these events between slides to ensure only the active slide has ...

How to use Javascript 'if statement' to check for a numerical value in a form field?

I am currently using some JavaScript within a Mongoose Schema to automatically increment a value if no number is manually entered in the form field. // before validation starts, the number of Items is counted..afterwards, the position is set ItemSche ...

The Google Maps Javascript API will only load data if the console is open

I'm facing an issue with displaying a map on my webpage where I want to set a marker. What's the problem Despite no errors in the console or from Google, the map data is not loading properly. All I see is the Google logo and a grey background, ...

Tips for transferring information between pages in AngularJS

I recently completed a blog project using angular-js. On one specific page, I have listed all the blogs and included functionality to edit or delete each entry. When clicking on these buttons, I intend to move to the next page and display the relevant data ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...

Developing a React component for distribution leads to a significantly increased build size compared to initial estimations

After loosely following a guide to create React components for distribution, I was surprised by the size of my webpack production build. The individual file sizes are small, but the final build is much larger than expected. My source js and less files comb ...

Is it possible to utilize a route path in a JavaScript AJAX request?

So I have a situation with an ajax call that is currently functioning in a .js file, utilizing: ... update: function(){ $.ajax({ url: '/groups/order_links', ... However, my preference would be to use the route path instead. To achieve ...

In my Google Sheets script, I am looking to introduce a 2-minute delay within the forEach loop for sending emails. Unfortunately, I have not had success

I am looking to introduce a 2-minute delay after each iteration of the loop. Specifically, I want to add a delay in the process of sending emails. You can find the complete code at this link. obj.forEach(function(row, rowIdx){ sleep(1200000); / ...

How come the hover feature in VS Code doesn't display the "null" part of my JSDoc type definition union?

Here is an example of a LinkedList class definition that utilizes JSDoc and jsconfig.json for type checking in VSCode. The issue lies in displaying the type of value and next as union types with undefined, which is not currently happening. class LinkedList ...

Prevent popup content from refreshing: Tips for creating a dynamic user experience

Currently, I am working on a website that is similar to Facebook. One of the features I am implementing is the ability for users to like posts or photos and see who has liked them. However, I am facing an issue with the popup that shows the list of people ...