Skip to content

Commit

Permalink
Create new SplitText instance on rerender
Browse files Browse the repository at this point in the history
  • Loading branch information
leroykorterink committed Jan 6, 2023
1 parent 75838d5 commit 28b380d
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions packages/react-animation/src/SplitTextWrapper/SplitTextWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
import { ensuredForwardRef } from '@mediamonks/react-hooks';
import gsap from 'gsap';
import SplitText from 'gsap/SplitText';
import { useCallback, type ReactElement } from 'react';
import { type ReactElement } from 'react';
import { renderToString } from 'react-dom/server';

gsap.registerPlugin(SplitText);

export type SplitTextWrapperProps = {
children: ReactElement;
variables?: SplitText.Vars;
};

export const SplitTextWrapper = ensuredForwardRef<SplitText | null, SplitTextWrapperProps>(
({ children, variables = {} }, ref): ReactElement => {
const onRef = useCallback(
async (element: HTMLDivElement) => {
if (ref.current && 'isSplit' in ref.current && ref.current.isSplit) {
return;
}
/**
* Not using useCallback on purpose so that a new SplitText instance is
* created whenever this component rerenders the children
*/
const onRef = async (element: HTMLDivElement): Promise<void> => {
if (ref.current && 'isSplit' in ref.current && ref.current.isSplit) {
return;
}

ref.current = new SplitText(element, variables);
},
[ref, variables],
);
ref.current = new SplitText(element, variables);
};

return (
<div
// eslint-disable-next-line react/jsx-no-bind
ref={onRef}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
Expand Down

0 comments on commit 28b380d

Please sign in to comment.