Unlock seamless workflows and faster delivery with our latest releases- get the details

How to implement split letter animations on block content text in React.

6 replies
Last updated: May 6, 2021
Any ideas on how to go about implementing split letter animations on block content text that includes marks and styles? Essentially I want to split the text strings into individual spans, one per letter, to achieve this sort of animation . I’ve accomplished that with a custom serializer but I lose the marks and styles
May 6, 2021, 7:41 PM
Here’s what I have so far in the serializer:
types: {
		block: (props: any) => {
			return (
				<span className="split-letters">
					{[...props.children].map((child) => {
						const text = child.props?.node?.children.join(" ");
						if (text) {
							return [...text].map((letter) => (
								<span className="letter">{letter}</span>
							));
						}
					})}
				</span>
			);
		},
	},
May 6, 2021, 7:41 PM
[Side note: That's a pretty sweet animation
user S
! 😄 ]
May 6, 2021, 7:53 PM
I got it working!
import React from "react";
// @ts-ignore
import SanityBlockContent from "@sanity/block-content-to-react";

export const SplitLetterSerializer = {
	types: {
		block: (props: any) => {
			const modifiedBlockContent = SanityBlockContent.defaultSerializers.types
				.block(props)
				.props.children.map((Block: React.ReactElement) => {
					let text;
					if (Block.props?.node?.children) {
						text = Block?.props?.node?.children.join(" ");
					}
					let modifiedText;
					if (text) {
						modifiedText = [...text].map((letter) => (
							<span className="letter">{letter}</span>
						));
					}
					if (Block.props?.node?.children) {
						Block.props.node.children = [modifiedText];
					}
					return Block;
				});

			return modifiedBlockContent;
		},
	},
};
May 6, 2021, 9:37 PM
Hey friends, GSAP also has an excellent plugin for this:

https://greensock.com/splittext/
May 6, 2021, 11:16 PM
Splitting.Js by Stephen Shaw is pretty popular too! https://splitting.js.org/
May 6, 2021, 11:20 PM
Thanks
user S
! I ended up getting it working without a library — I didn’t realize GSAP took HTML elements, same with splitting.js, but even so, I wanted to preserve the React Component
May 6, 2021, 11:22 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?