Enhance design based on scrolling function in React

I've been trying to update the color of my header when a user scrolls the page, but for some reason, my onScroll method isn't working. Can anyone help me figure out why and how to solve this issue? The onScroll method is triggered by the bottom TemplateWrapper component. And if you have any alternative suggestions on how to achieve this effect, I'm open to them! Thank you!

const headerStyle = {
      background: 'grey',
      marginBottom: '1.45rem',
      position: 'fixed',
      top: 0,
      left: 0,
      width: '100%',
      zIndex: '99'
}

const modHeader = () => {
  headerStyle.background = 'white'
  console.log('scroll')
}

const Header = () => (

  <div className='header'
    style={headerStyle}
  >
    <div
      style={{
        margin: '0 auto',
        maxWidth: 1160,
        padding: '1.45rem 1.0875rem',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between'
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
            to="/"
            style={{
              color: 'white',
              textDecoration: 'none',
            }}
          >
            Gatsby
        </Link>
      </h1>
      <h2 style={{ margin: 0 }}>  
        <Link
          to="/about"
          style={{
            color: 'white',
            textDecoration: 'none',
          }}
        >
          About
        </Link>
      </h2>
    </div>
  </div>
)

const TemplateWrapper = ({
  children
}) => (
    <div onScroll={modHeader}>
      <Helmet
        title="Gatsby Default Starter"
        meta={[
          { name: 'description', content: 'Sample' },
          { name: 'keywords', content: 'sample, something' },
        ]}
      />
      <Header />
      <div 
        style={{
          margin: '0 auto',
          maxWidth: 960,
          padding: '0px 1.0875rem 1.45rem',
          paddingTop: 0,
        }}
      >
        {children()}
      </div>
    </div>
  )

export default TemplateWrapper

Answer №1

To capture scroll events and update your component, you must add an event listener in the componentDidMount lifecycle method and store the value in the state:

componentDidMount = () => {
   window.addEventListener('scroll', ()=>{
     this.setState({
       // Add your flags here
      });
    });
   };

Note: If you need to attach an event listener to a specific div element in React, you can do so by using refs:

componentDidMount = () => {
   this.listener.addEventListener('scroll', ()=>{
     this.setState({
       // Add your flags here
      });
    });
   };
render(){
   return( 
       <div ref={(listener) => { this.listener = listener }}></div>
    )
 }

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

React Application - The division is positioned centrally when run on local host, however, it does not retain its center alignment

I'm encountering an issue with deploying my create-react-app on github pages. The first image showcases my deployed app on github pages, but the image is not properly centered on the page as intended. https://i.stack.imgur.com/rOciT.jpg On the othe ...

React callbacks involve the interaction between three different components

Currently, I am working with 3 distinct components: -The friendsPage component contains a list of friends and invitations to friends -The friendComponent displays detailed information about a friend along with possible actions (which are handled in the t ...

Tips on how to center an image within a table cell:1. Insert the image

I've been attempting to center an image within a bootstrap4 table cell, but it keeps appearing on the left and even overlaps the border. I've tried adding inline styles like text-align: center; vertical-align: middle; both to the table cell HTML ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

Using React and Redux to update the state of an object with the current state

Upon mounting my component, I make a call to an API and upon success, the state is updated with the following data: { "brief":"No brief given", "tasks":[ { "_id":"5c74ffc257a059094cf8f3c2", " ...

Sending an AJAX request to a REST service in order to submit the information captured in an HTML form

<html> <body> <form method="POST"> <label>username</lable> <input id="username" name="username" type="text"> <label>emailid</lable> <input id="emailid" ...

Struggling with creating an html file that is responsive on mobile devices

I am currently utilizing bootstrap 4 for the construction of a website. I have encountered an issue where my homepage does not display properly on handheld devices when using Google Chrome's device toggle toolbar. The homepage requires scrolling to vi ...

Applying Bootstrap classes to adjust font weight

Are there any pre-existing Twitter Bootstrap classes that can be used for styling font weight, such as font-weight: bold and other variations? I'd prefer not to reinvent the wheel if Bootstrap already has this capability. ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Angular directive that verifies the presence of a specific number of child li elements

Currently, I have a basic ul that utilizes ng-repeats to display li elements fetched from an external source via a promise. There is also a search input present which filters these elements, and I want the ul to be hidden when there are no more elements th ...

Navigating with jQuery Scrollbars

Looking to incorporate a bit of animation in jQuery, trying out the following line: window.parent.scroll(coord[0], coord[1]); The next block of code doesn't seem to be achieving what I had in mind. Do you have any suggestions? $(window.parent).anim ...

Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example: Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}] My goal is to create a table with the headers (num, name, phone) Is there a w ...

Is it possible to refresh data efficiently using web scraping tools, similar to how it

While researching web scraping in Python, I consistently found references to BeautifulSoup and Selenium as the primary tools for retrieving HTML and JavaScript content from websites. One thing that has eluded me is finding a method to automatically update ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

The parent div isn't properly extending to accommodate the table, and the columns aren't aligning correctly within the table when using CSS flexbox

I have a scenario where I need a table inside a div to take up the entire space of the div, with the second column and its inputs expanding as much as possible to fill the width (i.e. col1+col2 = div width). Due to being nested within another div, absolut ...

Difficulty in defining the header while using the submit hook in Remix 1.15

When I utilize the useSubmit hook to send a POST request, it appears that the header I specify is not being taken into account. Below is the code snippet for my submit function: submit('/dashboard/', { method: 'post', heade ...

Ensure that at least one mandatory field is implemented with React final form

Here is a code snippet that handles field validation: export const isOneFieldValid = (val: string) => { console.log(val) return val ? undefined : true } ... const validate = (field: string) => { switch (field) { case 'email': { ...

Creating JavaScript Powered Pie Charts

I am seeking a lightweight JavaScript pie chart option to replace PlotKit, as the library is too large for my low bandwidth. Ideally, I am looking for a compact and efficient solution in either JavaScript or jQuery. ...