Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  48] [ 6]  / answers: 1 / hits: 36040  / 7 Years ago, sun, june 18, 2017, 12:00:00

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...



  import React, { Component } from 'react';

class App extends Component {

constructor(props) {
super(props);

this.state = { scrollBackground: 'nav-bg' };
this.handleScroll = this.handleScroll.bind(this);
}


handleScroll(){
this.setState ({
scrollBackground: !this.state.scrollBackground
})
}

render() {
const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';

return (
<div>

<Navbar inverse toggleable className={this.state.scrollBackground}
onScroll={this.handleScroll}>
...
</Navbar>

</div>
);
}
}

export default App;

More From » reactjs

 Answers
35

One way to add a scroll listener is to use the componentDidMount() lifecycle method. Following example should give you an idea:



import React from 'react';
import { render } from 'react-dom';

class App extends React.Component {
state = {
isTop: true,
};

componentDidMount() {
document.addEventListener('scroll', () => {
const isTop = window.scrollY < 100;
if (isTop !== this.state.isTop) {
this.setState({ isTop })
}
});
}
render() {
return (
<div style={{ height: '200vh' }}>
<h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
</div>
);
}
}

render(<App />, document.getElementById('root'));


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.


[#57403] Friday, June 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kileyr

Total Points: 112
Total Questions: 105
Total Answers: 114

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;