I’m using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn’t find that much info on it. So far I have…
I don’t know if I’m using the right event listener or how to set the height etc.
And I’m not really setting inline styles…
JavaScript
x
36
36
1
import React, { Component } from 'react';
2
3
class App extends Component {
4
5
constructor(props) {
6
super(props);
7
8
this.state = { scrollBackground: 'nav-bg' };
9
this.handleScroll = this.handleScroll.bind(this);
10
}
11
12
13
handleScroll(){
14
this.setState ({
15
scrollBackground: !this.state.scrollBackground
16
})
17
}
18
19
render() {
20
const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';
21
22
return (
23
<div>
24
25
<Navbar inverse toggleable className={this.state.scrollBackground}
26
onScroll={this.handleScroll}>
27
28
</Navbar>
29
30
</div>
31
);
32
}
33
}
34
35
export default App;
36
Advertisement
Answer
One way to add a scroll listener is to use the componentDidMount()
lifecycle method. Following example should give you an idea:
JavaScript
1
27
27
1
import React from 'react';
2
import { render } from 'react-dom';
3
4
class App extends React.Component {
5
state = {
6
isTop: true,
7
};
8
9
componentDidMount() {
10
document.addEventListener('scroll', () => {
11
const isTop = window.scrollY < 100;
12
if (isTop !== this.state.isTop) {
13
this.setState({ isTop })
14
}
15
});
16
}
17
render() {
18
return (
19
<div style={{ height: '200vh' }}>
20
<h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
21
</div>
22
);
23
}
24
}
25
26
render(<App />, document.getElementById('root'));
27
This changes the Text from “Scroll down” to “Scroll up” when your scrollY position is at 100 and above.
Edit: Should avoid the overkill of updating the state on each scroll. Only update it when the boolean value changes.