import React, { useRef, useState, useEffect } from "react"; export interface SegmentControlProps { segments: { id: string; label: string }[]; value: string; onClick?: (segment: string) => void; } export const SegmentControl = (props: SegmentControlProps) => { const index = props.segments.findIndex((seg) => seg.id === props.value); // Initialize approximate segment width const [segmentWidth, setSegmentWidth] = useState( 480 / props.segments.length, ); const containerRef = useRef(null); if (index === -1) { throw new Error( `Unknown SegmentControl id ${props.value} for segments ${JSON.stringify( props.segments, )}`, ); } // Update segment width when container is fully rendered useEffect(() => { if (containerRef.current?.clientWidth) setSegmentWidth(containerRef.current.clientWidth / props.segments.length); }, [containerRef.current]); return (
{props.segments.map((segment) => ( ))}
); };