Skip to content
Advertisement

Output string after sring.split(“”).map breaks into pieces on small screens

With great help from @pratik-wadekar I have the following working text animation. Now my problem is that when I test it on different screen sizes/mobile the animated word plants breaks into pieces. For example PLA and in the next line NTS. How can I avoid this? So it always keeps as one full word.

First I tried to add xC2xA0 – non-breaking space or   before and after the word but this doesnt help. The CSS word-wrap property allows long words to be able to break but unfortunately for the reverse case to make a word unbreakable there is no option.

It seems that the CSS word-break: "keep-all property is what I need but when I apply it, it still breaks into pieces on smaller screens.

The Codepen

And App.tsx:

import React from "react";
import { styled } from "@mui/material/styles";
import { Typography } from "@mui/material";

const AnimatedTypography = styled(Typography)`
 & {
   position: relative;
   -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2));
   font-size: 60px;
 }

 & span {
   color: #fbbf2c;
   font-family: "Alfa Slab One", sans-serif;
   position: relative;
   display: inline-block;
   text-transform: uppercase;
   animation: waviy 1s infinite;
   animation-delay: calc(0.1s * var(--i));
 }

 @keyframes waviy {
   0%,
   40%,
   100% {
     transform: translateY(0);
   }
   20% {
     transform: translateY(-20px);
   }
 }
`;

interface Styles extends React.CSSProperties {
 "--i": number;
}

function App() {
 const string = "plants";
 return (
   <Typography variant={"h3"} fontWeight={"bold"}>
     All Your
     <AnimatedTypography>
       {string.split("").map((char, idx) => {
         const styles: Styles = {
           "--i": idx + 1
         };
         return (
           <span key={`${char}-${idx}`} style={styles}>
             {char}
           </span>
         );
       })}
     </AnimatedTypography>
     in One Place
   </Typography>
 );
}

export default App;



Advertisement

Answer

Ok I got it. I had to make the animation as own component and add the <AnimatedTypography> the component={"span"} type and white-space: nowrap. Additionally to my const AnimatedTypography = styled(Typography) I had to cast the resulting component with as typeof Typography so Typescript does not throws errors. See here: Complications with the component prop

Then importing the component and addind into the Typography component between my text. Now the layout of my text is preserved and the animation does not split into single characters.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement