I want to use IntersectionObserver to reload CSS animation on scroll. I have faced the following thing:
At the moment, the only right working place for IntersectionObserver is after ReactDOM.render() in my index.jsx.
observer.js :
const observerHTML = new IntersectionObserver(entries => {
entries.forEach(entry => {
const html = entry.target.querySelector('#progress-bar-html')
if (entry.isIntersecting) {
html.classList.add('html__animation')
return
}
html.classList.remove('html__animation')
})
})
observerHTML.observe(document.querySelector('.html'))
index.jsx :
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app/App'
import observers from './utils/observers'
import './styles/reset.styles.css'
import './styles/index.css'
import './styles/scrollbar.css'
import './styles/animations.css'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)
observers()
Are there any other possible ways to implement it inside the exact component which should be observed for changing CSS styles?
I have some amount of such components and want to make observer to be reusable in order no to make it very big. Like “God” function for all components. Instead, every component will reuse it. But the problem is, if I put IntersectionObserver inside the exact component, React renders completely nothing. ♂️
exact-components.jsx:
import React from 'react'
import observers from '../../../utils/observers'
function HTML() {
observers()
return (
<div className='timeline-container-two html'>
<div className='timeline-icon'>
<i className='fab fa-html5'></i>
</div>
<div className='timeline-body'>
<h4 className='timeline-title'>
<span className='badge'>HTML</span>
</h4>
<p>
The very beginning. There is not much to emphasize here, except that
without familiarity with HTML5, it would be difficult to imagine
building web pages or entire sites.
</p>
<div className='progress'>
<div
id='progress-bar-html'
className='progress-bar'
role='progressbar'
style={{ width: '80%' }}
aria-valuenow='80'
aria-valuemin='0'
aria-valuemax='100'>
Overall progress: 80%
</div>
</div>
<p className='timeline-subtitle'>September 2020</p>
</div>
</div>
)
}
export default HTML