function Switch({ options, value, onChange }) {
const highlight = useRef();
useEffect(() => {
const activeButton = highlight.current.closest('.c-switch').querySelector('.is-active');
highlight.current.style.width = `${activeButton?.offsetWidth ?? 0}px`;
highlight.current.style.transform = `translateX(${activeButton?.offsetLeft ?? 0}px)`;
}, [ value ]);
return (
<div className="c-switch">
<div className="c-switch__highlight" ref={highlight}></div>
{options.map(n => (
<button
key={n.value}
className={n.value === value ? 'is-active' : ''}
onClick={() => onChange(n.value)}
>{n.text}</button>
))}
</div>
);
}
https://jsfiddle.net/4hbkm9e8/