Skip to content

Instantly share code, notes, and snippets.

@daniloab
Created March 6, 2020 14:34
Show Gist options
  • Save daniloab/7c48ea17dde9f9b51076078f85670384 to your computer and use it in GitHub Desktop.
Save daniloab/7c48ea17dde9f9b51076078f85670384 to your computer and use it in GitHub Desktop.
type Props = {
labels: string[];
}
const ScaleButtons = ({labels}:Props) => {
const [isCalculating, setIsCalculating] = useState<boolean>(true);
const [width, setWidth] = useState<number>(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setWidth(node.getBoundingClientRect().width);
}
return setIsCalculating(false);
}, []);
const getBiggerTextWidth = () => {
return labels.reduce((acc, cur) => {
if (cur.label.length >= acc.length) {
return cur.label;
}
return acc;
}, '');
};
if (isCalculating) {
const biggestText = getBiggerTextWidth();
return <span ref={measuredRef}>{biggestText}</span>;
}
const range = labels.length;
const renderLabel = (position: number) => {
return labels[position];
};
const renderButton = (position: number) => {
return (
<Button
key={position}
width={width}
>
{renderLabel(position)}
</Button>
);
};
return (
<Flex>
{range.map((_, index) => renderButton(index))}
</Flex>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment