maxeth / react-type-animation

A React typewriter animation based on typical with extended functionality and customization.
https://react-type-animation.netlify.app/
MIT License
353 stars 25 forks source link

Hide cursor on typing completion #14

Closed syedddda closed 1 year ago

syedddda commented 1 year ago

Hi, the cursor option allows us to show or hide the cursor when the text is being typed. But when I set the cursor prop's value from a state and change the state at the end of animation, it doesn't hide the cursor.

For example, I want the cursor to show up when the text is being typed but hide it after the typing completes. I guess the cursor show and hide needs to be updated using a useEffect when the prop changes from the consuming component. See below code for understanding.

type typingTextType = string | number;

interface TypingAnimationProps {
  typingText: typingTextType;
  onComplete?: Function;
  hideCursorOnEnd?: boolean;
}

export const TypingAnimation: React.FC<TypingAnimationProps> = (props) => {
  const { typingText, onComplete, hideCursorOnEnd = false } = props;
  const [hideCursor, setHideCursor] = useState(false);

  return (
    <TypeAnimation
      sequence={[
        typingText,
        1000,
        () => {
          onComplete && onComplete(true);
          hideCursorOnEnd && setHideCursor(true);
        },
      ]}
      wrapper="span"
      className={cssClasses.APP_TYPING_ANIMATION}
      cursor={!hideCursor}
      speed={1}
      omitDeletionAnimation
    />
  );
};
maxeth commented 1 year ago

Hey,

as stated on the npm page you can't update any props after the initial render:

Due to the nature of the animation, this component is permanently memoized, which means that the component never re-renders unless you hard-reload the page, and hence props changes will not be reflected

You should be able to achieve disabling the cursor animation after some time by doing the following:

assuming the value of APP_TYING_ANIMATION_BLINKING_CURSOR was type-animation-cursor, the css should have rules like these:

.type-animation-cursor::after {
  content: '|';
  animation: cursor 1.1s infinite step-start;
}

@keyframes cursor {
  50% {
    opacity: 0;
  }
}

I hope that works with your styling solution.

syedddda commented 1 year ago

@maxeth Yes that works! But, if you had forwarded ref and set it to the parent div, would it work for me to do the same class adding and removing with ref instead of document.getElementsByClassName? That would be much cleaner to do.

maxeth commented 1 year ago

@maxeth Yes that works! But, if you had forwarded ref and set it to the parent div, would it work for me to do the same class adding and removing with ref instead of document.getElementsByClassName? That would be much cleaner to do.

Hey, I'll note this down and may add a forwardRef in the next version.

syedddda commented 1 year ago

@maxeth Thanks!