DEV Community

fazuelinton
fazuelinton

Posted on

Simple text blinking animation using styled-components

tl;dr

import React from 'react';
import styled, { keyframes } from 'styled-components'

function blinkingEffect() {
  return keyframes`
    50% {
      opacity: 0;
    }
  `;
}

const AnimatedComponent = styled.div`
  animation: ${blinkingEffect} 1s linear infinite;
`
const App = () => {
  return (
    <AnimatedComponent>_</AnimatedComponent>
  )
}
Enter fullscreen mode Exit fullscreen mode

Issue

My app is pretty simple and I created it for learning purposes.
The user must enter a binary value and the app converts the value into a decimal number. You can try it here: https://jovial-wilson-a92dc1.netlify.app/

After adding the main functionalities I wanted to use CSS to animate the output field.
The output field must show a blinking underscore character until the user types a valid binary value
Alt Text

Solution

I first added styled-components to the project:

yarn add styled-components
Enter fullscreen mode Exit fullscreen mode

Then I imported styled-components' styled and keyframes into my App:

import styled, { keyframes } from 'styled-components'
Enter fullscreen mode Exit fullscreen mode

For keyframes to work with styled-components, I created a function outside of my App:

function blinkingEffect() {
  return keyframes`
    50% {
      opacity: 0;
    }
  `;
}
Enter fullscreen mode Exit fullscreen mode

You can name the function whatever. Remembering that keyframes is a CSS concept. Keyframes controls the intermediate steps in a CSS animation.

Our animation is defined after as a styled component and it references our keyframes function blinkingEffect declared before:

const AnimatedComponent = styled.div`
  animation: ${blinkingEffect} 1s linear infinite;
`
Enter fullscreen mode Exit fullscreen mode

Lastly, I created our react App which returns the AnimatedComponent and some text - that will blink according to the implementation:

const App = () => {
  return (
    <AnimatedComponent>_</AnimatedComponent>
  )
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is a pretty simple app and animation for learning purposes. I googled text-blink animation and didn't find the solution exactly, so I created this post. I hope it helps you too!

The code posted here isn't functional since you have to configure your app using create-react-app or something similar.

You can find the convert binary to decimal app code here: https://github.com/veller/app-ideas-Bin2Dec

Here's another source that helped me to get to the solution: https://github.com/styled-components/styled-components/issues/14

Top comments (0)