Skip to content

Commit

Permalink
rework logic of waiting for ref
Browse files Browse the repository at this point in the history
  • Loading branch information
bitttttten committed Oct 22, 2021
1 parent 9244198 commit 814cf95
Showing 1 changed file with 30 additions and 30 deletions.
60 changes: 30 additions & 30 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,47 +22,34 @@ export function MechanicalCounter({
// we need to wait until we have the ref
// so we can calculate the font height
useEffect(() => {
if (isLoaded) {
return void 0;
}

let isMounted = true;
while (!ref.current && isMounted) {}
set(true);
return () => {
isMounted = false;
};
}, [ref]);
}, []);

const placeholder = (
<span
style={{
color: "transparent",
position: `absolute`,
top: 0,
left: 0,
height,
lineHeight: typeof height === "string" ? height : `${height}px`,
}}
ref={ref}
>
{text}
</span>
);
const baseStyles = {
height,
lineHeight: typeof height === "string" ? height : `${height}px`,
};

if (!isLoaded) {
return placeholder;
// it's opacity 0 since we only really want to get the ref
// to calculate the font height
return (
<div>
<span style={{ ...baseStyles, opacity: 0 }} ref={ref}>
{text}
</span>
</div>
);
}

return (
<motion.div
animate={{
initial={{
width: totalWidth,
}}
initial={{
animate={{
width: totalWidth,
}}
exit={{ width: 0, opacity: 0 }}
transition={{ ease: "easeOut" }}
style={{
overflow: "hidden",
Expand All @@ -71,7 +58,20 @@ export function MechanicalCounter({
lineHeight: typeof height === "string" ? height : `${height}px`,
}}
>
{placeholder}
<span
style={{
color: "transparent",
position: `absolute`,
top: 0,
left: 0,
height,
lineHeight: typeof height === "string" ? height : `${height}px`,
}}
ref={ref}
>
{" "}
{text}
</span>
<AnimatePresence initial={false}>
{textArray.map((letter, index) => {
const left = stats.slice(0, index).reduce(count, 0);
Expand Down

0 comments on commit 814cf95

Please sign in to comment.