Home > Software design >  A blinking text with React using the CSS property visibility
A blinking text with React using the CSS property visibility

Time:12-29

I want to code a blinking text that blinks every second using React throw the CSS property (visibility), I want to implement it in this exact approach, here is what I want to do:

Where is the mistake ? I also tried setTimeout but it didn't work as well.

import { useState, useEffect } from "react";

function Blink(props) {
  const [state, setState] = useState("hidden");

  useEffect(() => {

    setInterval(() => {

      setState("visible");
      console.log("changed");

    }, 1000);

    return () => clearInterval();
  }, [state]);

  return <span style={{ visibility: state }}>{props.children}</span>;

}


function App() {
  return <Blink>Hello World!</Blink>;
}

CodePudding user response:

Your setInterval doesn't alternate the state between "visible" and "hidden". All it does it set the state to "visible" over and over again. You need to take the current state into account. The easiest way, I think, would be to make it a boolean (useState(false)) and then in the setInterval, have it setState(!state).

Then all you need to do is change the style to {{ visibility: state ? 'hidden' : 'visible' }}.

CodePudding user response:

You have missed to clear the state (toggle visible/hidden). I think you should try something like this:

setState(state == 'visible' ? 'hidden' : 'visible')
  • Related