DEV Community

Matthew Cullen
Matthew Cullen

Posted on • Edited on

13 2

Create a 'user is typing...' animation with React and CSS

Alt Text
Today I am going to show you how to create an animation to show that a user is typing. If you have used chat rooms like Slack or Discord you may have noticed this effect.

First let's assume we have a chat box component that is listening and updating a value in state to indicate if a user is typing or not.



class ChatBox extends React.Component {
    state = {
        isTyping: false
    }

    render() {
        <div><div>
    }
}


Enter fullscreen mode Exit fullscreen mode

Next lets make the typing animation component. Essentially this will be a div with 3 divs in it. Some css tricks will turn it into a rectangle with 3 dots in it though.



const Typing = () => (
  <div className="typing">
    <div className="typing__dot"></div>
    <div className="typing__dot"></div>
    <div className="typing__dot"></div>
  </div>
)


Enter fullscreen mode Exit fullscreen mode

Now some css to style and animate our three divs.



.typing {
  width: 5em;
  height: 2em;
  position: relative;
  padding: 10px;
  margin-left: 5px;
  background: #e6e6e6;
  border-radius: 20px;
}

.typing__dot {
  float: left;
  width: 8px;
  height: 8px;
  margin: 0 4px;
  background: #8d8c91;
  border-radius: 50%;
  opacity: 0;
  animation: loadingFade 1s infinite;
}

.typing__dot:nth-child(1) {
  animation-delay: 0s;
}

.typing__dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing__dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes loadingFade {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 0.8;
  }
  100% {
    opacity: 0;
  }
}


Enter fullscreen mode Exit fullscreen mode

Last step is to add our animation in to our ChatBox when this.state.isTyping is true.



class ChatBox extends React.Component {
    state = {
        isTyping: false
    }

    render() {
          const { isTyping } = this.state;

          return (
          <div> { isTyping ? <Typing /> : null } <div>
    )}
}


Enter fullscreen mode Exit fullscreen mode

And that's all there is to it!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay