<div id="root">
</div>
div.box {
position: relative;
left: 50%;
width: 400px;
height: 200px;
margin-left: -420px;
margin-bottom: 30px;
background-color: rgba(22, 22, 22, 1);
color: white;
font-size: 30px;
font-weight: bold;
text-align: center;
line-height: 200px;
}
ul {
position: fixed;
top: 50%;
right: 50%;
width: 300px;
height: 170px;
margin: -85px -400px 0 0;
padding: 40px;
border: 1px solid black;
}
li {
margin-bottom: 10px;
}
span.false {
color: red;
}
span.true {
color: green;
}
const { useEffect, useState, useRef } = React
const thresholdArray = () => {
const threshold = []
for (let i=0; i<=1; i += 0.01) threshold.push(i)
return threshold
}
const EachDiv = ({ id, update, children }) => {
const ref = useRef(null)
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
entry.target.style.backgroundColor = `rgba(22, 22, 22, ${entry.intersectionRatio})`
update(prev => ({
...prev,
[entry.target.id]: String(entry.isIntersecting)
}))
})
},
{
threshold: thresholdArray()
})
observer.observe(ref.current)
return () => observer.unobserve(ref.current)
}, [])
return <div class={'box'} id={id} ref={ref}>{children}</div>
}
const App = () => {
const [divVisibility, setDivVisibility] = useState({
div1: 'false',
div2: 'false',
div3: 'false',
div4: 'false',
div5: 'false',
div6: 'false',
})
return (
<>
{[1,2,3,4,5,6].map(n =>
<EachDiv id={`div${n}`} update={setDivVisibility}>{n}</EachDiv>
)}
<ul>
{[1,2,3,4,5,6].map(n => (
<li>
div {n}:{' '}
<span className={divVisibility[`div${n}`]}>{divVisibility[`div${n}`]}</span>
</li>
))}
</ul>
</>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
View Compiled
This Pen doesn't use any external CSS resources.