Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  118] [ 6]  / answers: 1 / hits: 42600  / 6 Years ago, fri, january 26, 2018, 12:00:00

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?


More From » css

 Answers
56

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.


[#55349] Wednesday, January 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dewayneh

Total Points: 538
Total Questions: 114
Total Answers: 97

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;