Skip to content

Instantly share code, notes, and snippets.

@gubser
Created October 21, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gubser/257e1022f84b8f13e89b0b8e43aaca10 to your computer and use it in GitHub Desktop.
Save gubser/257e1022f84b8f13e89b0b8e43aaca10 to your computer and use it in GitHub Desktop.
Create auto-wrapping text in SVG
import React from 'react';
import { isArray } from 'lodash';
export function wrapText(s: string|undefined, maxLength: number): string[] {
if(s === undefined) {
return [];
} else if(s.length < maxLength) {
return [s];
} else {
const lastSpaceIndex = s.lastIndexOf(' ', maxLength);
if(lastSpaceIndex === -1) {
return [
s.substring(0, maxLength),
...wrapText(s.substring(maxLength), maxLength)
];
} else {
return [
s.substring(0, lastSpaceIndex),
...wrapText(s.substring(lastSpaceIndex+1), maxLength)
];
}
}
}
export interface WrappedTextProps extends React.SVGProps<SVGTextElement> {
children: string|string[];
maxLength?: number;
}
export function WrappedText({ children, maxLength, ...rest }: WrappedTextProps) {
if(isArray(children)) {
if(children.length === 0) {
return <></>;
} else {
return (
<text {...rest}>
{children.map((s, i) => <tspan key={i} x="0" dy="1.2em">{s}</tspan>)}
</text>
);
}
} else {
return (
<text {...rest}>
{wrapText(children, maxLength || 80).map((s, i) => <tspan key={i} x="0" dy="1.2em">{s}</tspan>)}
</text>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment