La couleur de fond change dynamiquement quand chaque section entre dans le viewport.
"use client";
import { useRef, useState, useEffect } from "react";
const colors = ["#1a1a2e", "#16213e", "#0f3460", "#533483", "#e94560"];
export default function ColorSwapper() {
const containerRef = useRef<HTMLDivElement>(null);
const [bgColor, setBgColor] = useState(colors[0]);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const sections = container.querySelectorAll("[data-color]");
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setBgColor(entry.target.getAttribute("data-color") || colors[0]);
}
});
}, { root: container, threshold: 0.5 });
sections.forEach((s) => observer.observe(s));
return () => observer.disconnect();
}, []);
return (
<div ref={containerRef} style={{ backgroundColor: bgColor, transition: "background-color 0.8s" }}>
{colors.map((color, i) => (
<section key={i} data-color={color}>Section {i + 1}</section>
))}
</div>
);
}Chaque section a un data-color. L'IntersectionObserver (threshold 0.5) detecte quelle section est visible et change le fond. Transition 0.8s pour un changement fluide.