19

Is it possible to change the class of my header so that it will change its color when the background changes? I have a header and some sections. The header is fixed and when it foreaxmple reaches a section with a different backgroundcolor, I want to change the headers color for better readability, but I don't know how to do that. I've searched the web for it but I couldn't eally find something.

this is what I got so far: (see this JSFIDDLE )

class Div extends React.Component{
   constructor() {
     super()

     this.state = {
       headerClass: 'white'
     }
}
changeColor() {
  // something like
     this.setState({ headerClass: 'black'})
}
render(){
  return(
    <div>
      <div id="header">
        <h1 className={`${this.state.headerClass}`}>
          This is the header
        </h1>
     </div>      
     <div id="section_1" className="section">
        This is section 1
     </div>

     <div id="section_2" className="section">
        This is section 2
     </div>

     <div id="section_3" className="section">
        This is section 3
     </div>

     <div id="section_4" className="section">
        This is section 4
     </div>

     <div id="section_5" className="section">
        This is section 5
     </div>

   </div>
   )
 }
}

the CSS:

#main {
 height: 2000px;
 position: relative;
}

#section_1 {
  background: grey;
}

.section {
  height: 400px;
  background: white;
  padding: 30px 0;
}

#header {
  height: 50px;
  background: transparent;
  position: fixed;
  width: 100%;
  left: 0;
  top: 0;
  right: 0;
  z-index: 1
}

h1 {
 color: white;
}

So, are there any hints?

4
  • Bind a scroll event, check whether the desired element is visible or not, if visible they call setState.
    – learner
    Commented Jan 26, 2018 at 9:46
  • @learner What if multiple sections are visible at the same time? Then this solution will not work properly.
    – trixn
    Commented Jan 26, 2018 at 9:47
  • What do you want to do in this case? what do you mean by multiple sections? Do you want to check for only backgroundcolor? In that case you can check for: myDiv.style.backgroundColor.
    – learner
    Commented Jan 26, 2018 at 9:48
  • @learner He wants to change the color of his text in the header when it reaches a new section with a different background color for better contrast.
    – trixn
    Commented Jan 26, 2018 at 9:54

7 Answers 7

28

Try this:

import React from 'react'

export default class Div extends React.Component{
  state = {
    color: 'white'
  }

  listenScrollEvent = e => {
    if (window.scrollY > 400) {
      this.setState({color: 'black'})
    } else {
      this.setState({color: 'white'})
    }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.listenScrollEvent)
  }

  render() {
    return(
      <div>
        <div id="header">
          <h1 style={{color: this.state.color}}>
            This is the header
          </h1>
       </div>
       <div id="section_1" className="section">
          This is section 1
       </div>

       <div id="section_2" className="section">
          This is section 2
       </div>

       <div id="section_3" className="section">
          This is section 3
       </div>

       <div id="section_4" className="section">
          This is section 4
       </div>

       <div id="section_5" className="section">
          This is section 5
       </div>

     </div>
     )
   }
}

Basically we just use window.scrollY to know where has the user scrolled to.

4
  • 1
    How do you know that a section starts at 400? The sections could have dynamic content making their hight differ.
    – trixn
    Commented Jan 26, 2018 at 10:32
  • @trixn exactly! hmm maybe I somehow can pass the height of the sections as a prop!?
    – ST80
    Commented Jan 26, 2018 at 10:36
  • @Steve See my answer. Just make the sections decide when to change the color because they know their own size after render. Alternatively you have to pass though the ref of the sections to their parent and do calculation there.
    – trixn
    Commented Jan 26, 2018 at 10:38
  • But this is not responsive, what if section 1 changes height?
    – William
    Commented May 16, 2023 at 1:54
8

You could do this with React Hooks. This is what I did below.

Here is a Code SandBox to see all files. It has body.js and styles.css to help show changes on scroll. Below is the Header Component and its css file. Hope this Helps! (https://codesandbox.io/s/header-change-color-onscrolly-2z3vt)

// Header Component

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

import "./Header.css"

function Header2() {
const [header, setHeader] = useState("header")

const listenScrollEvent = (event) => {
  if (window.scrollY < 73) {
    return setHeader("header")
  } else if (window.scrollY > 70) {
    return setHeader("header2")
  } 
}

useEffect(() => {
  window.addEventListener('scroll', listenScrollEvent);

  return () =>
    window.removeEventListener('scroll', listenScrollEvent);
}, []);

  return (
    <header className={header}>
      <div className="logo">Logo</div>
      <ul className="links">
        <li className="link-item">home</li>
        <li className="link-item">about</li>
        <li className="link-item">join</li>
      </ul>
    </header>
  );
}

export default Header2;

css file.

// Styles header.css

.header {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 120px;
  background-color: #fff;
  color: #333;
  transform: translateY(0);
  transition: transform 0.6s ease;
}

.header2 {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 86px;
  background-color: gray;
  color: rosybrown;
  transform: translateY(10);
  transition: transform 6s ease;
  animation: myanimation 3s;
}
@keyframes myanimation {
  0% {
    background-color: transparent;
    color: transparent;
  }
  35% {
    background-color: gray;
    color: rosybrown;
  }
  100% {
    background-color: gray;
    color: rosybrown;
  }
}

.logo {
  margin: 0 24px;
  font-size: 28px;
  color: #f59596;
}

.links {
  padding: 0;
  margin: 0 24px;
}

.link-item {
  display: inline-block;
  margin: 0 12px;
  cursor: pointer;
}

3

The answer using hooks in React 16

import React from 'react'

export default Div => (){
  const [headerColor, setHeaderColor] = useState("white")


const listenScrollEvent = () => {
    window.scrollY > 10
      ? setHeaderColor("black")
      : setHeaderColor("white")
  }
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
  window.addEventListener("scroll", listenScrollEvent)
})

render() {

return(
  <div>
    <div id="header">
      <h1 style={{color: headerColor}}>
        This is the header
      </h1>
   </div>
   <div id="section_1" className="section">
      This is section 1
   </div>

   <div id="section_2" className="section">
      This is section 2
   </div>

   <div id="section_3" className="section">
      This is section 3
   </div>

   <div id="section_4" className="section">
      This is section 4
   </div>

   <div id="section_5" className="section">
      This is section 5
   </div>

 </div>
 )
 }
}
0
1

You could make your sections own components that keep a reference to their DOM element. Your Section component could then listen to a scroll event and invoke a callback that it has been given by the parent container when the top of your components DOM element reaches your fixed header.

Your Section component could look something like this.

class Section extends React.Component {

    ref = node => {
        this.ref = node;
        window.addEventListener('scroll', this.onScroll);
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.onScroll);
    }

    onScroll = event => {
        const {changeHeaderColor} = this.props;
        // calculate if the top value is inside your header by using the ref
        if (...) {
            changeHeaderColor();
        }
    }

    render() {
        const {id, children} = this.props;

        return (
            <div id={id} className="section" ref={this.ref}>{children}</div>
        );
    }
}

Then you could render your sections like this:

<Section id="section-1" changeHeaderColor={this.changeColor}> content here </Section>
0

This is how I would go:

I will bind a function on scroll in componentDidMount:

window.addEventListener("scroll", this.boundFun, false);

I will defined the function and add reference in constructor:

constructor:

    this.boundFun = this.scrollListingFun.bind(this);

I will add logic in:

scrollListingFun() {
  //  add logic for checks here.
}
2
  • 1
    But OP wants to change the color, when his fixed header reaches a certain section. So he needs to know the position of his section divs relative to the header element to check if the text color needs to change. This will only work with refs.
    – trixn
    Commented Jan 26, 2018 at 9:58
  • I think my answer is incomplete. By the way, OP was asking for a hint. I gave him the one. :)
    – learner
    Commented Jan 26, 2018 at 10:01
0

Try This `import React, { useState } from 'react'; import './Navbar.css';

const NavBar = () => {

const [navbar, setNavbar] = useState(false);
const [TextHome,setTextHome]=useState(false);
const [TextAbout,setTextAbout]=useState(false);
const [TextService,setTextService]=useState(false);
const [TextPortfolio,setTextPortfolio]=useState(false);
const [TextContact,setTextContact]=useState(false);


const changeBackground = () => {
    if (window.scrollY >= 200) {
        console.log(window.scrollY);
        setNavbar(true);
        setTextHome(true);
         if (window.scrollY >= 600 && window.scrollY <= 920 ) {
            setTextAbout(true);
            setTextService(false);
            setTextPortfolio(false);
            setTextContact(false);




        }
        else if (window.scrollY >=921 && window.scrollY <= 1500 ) {
            setTextService(true);
            setTextAbout(false);
            setTextPortfolio(false);
            setTextContact(false);


        }
        else if (window.scrollY >= 1501 && window.scrollY <= 2250) {
            setTextPortfolio(true);
            setTextService(false);
            setTextAbout(false);
            setTextContact(false);

        }
        else if (window.scrollY >= 2251) {
            setTextContact(true);
            setTextPortfolio(false);

        }
        else {
            setTextAbout(false);
            setTextService(false);
            setTextPortfolio(false);
            setTextContact(false);



        }

    }

    else {
        setNavbar(false);
        setTextHome(false);
        // setTextAbout(false);
        // setTextService(false);
        // setTextPortfolio(false);
        // setTextContact(false);



    }
};
window.addEventListener('scroll', changeBackground);




return (
    <nav className={navbar ? "navbar active navbar-expand-lg navbar-light fixed-top py-3" : "navbar navbar-expand-lg navbar-light fixed-top py-3"} id="mainNav">
        <div className="container">
            <Link smooth className="navbar-brand nav-link " to="/#app">Start Bootstrap</Link>
            <button className="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span className="navbar-toggler-icon"></span></button>
            <div className="collapse navbar-collapse" id="navbarResponsive">

                    <ul className="navbar-nav ml-auto my-2 my-lg-0">
                        <li className="nav-item active"><Link smooth className="nav-link" style={{color:TextHome?"orange":"#000"}} to="/#app">Home</Link></li>
                        <li className="nav-item"><Link smooth className="nav-link  " style={{color:TextAbout?"orange":"#000"}}  to="/#about">About</Link></li>
                        <li className="nav-item"><Link smooth className="nav-link  " style={{color:TextService?"orange":"#000"}}  to="/#services">Services</Link></li>
                        <li className="nav-item"><Link smooth className="nav-link  " style={{color:TextPortfolio?"orange":"#000"}} to="/#portfolio">Portfolio</Link></li>
                        <li className="nav-item"><Link smooth className="nav-link  " style={{color:TextContact?"orange":"#000"}}  to="/#contact">Contact</Link></li>
                </ul>
            </div>
        </div>
    </nav>
);

} export default NavBar;`

0

Here is another concise way of doing change the background color of the header.

useEffect(() => {
    let header = document.getElementById("header");
    window.addEventListener("scroll", () => {
      if (window.scrollY > 100) {
        header.style.background = "red"
      } else {
        header.style.background = "transparent"
      }
    })
  })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.