1

What I'm trying to do is that the background color inside the box stays colored for 0.5 seconds and then disappears. like When you click the YouTube comment alarm, the background color inside the box disappears.

when first rendering

there is background color enter image description here

0.5 second later background color disappear like this

enter image description here

this is my code

    const Container = styled.View`
    border-bottom-color: lightblue;
    `;
    const CommentContainer = styled.View`
    `;

    const SecondCommentCon = styled.View`
    `;

    const UnserName = styled.Text`
    `;
    const Label = styled.Text`
    `;

    const TodoList = ({}) => {

      return (

      <Container>
      <CommentContainer>
      <SecondCommentCon>
      <UnserName>{yes?.[0]?.User?.nickname}</UnserName>
      <Label>{yes?.[0]?.content}</Label>
      </SecondCommentCon>
      </CommentContainer>
      </Container>

      )
      

what code should i add??

jack volten
  • 267
  • 2
  • 13

1 Answers1

1

You could use setTimeout() to change the background color of the element by its className after a specified time.

First, define a class in a CSS file with the background color you want the element to be on mount

.bg-onmount {
  background-color: aquamarine;
}

Make sure you import this file (import "./App.css" for example).

Then you declare a state variable with an initial value of the class name you defined

// a state variable for the background class
const [backgroundClass, setBackgroundClass] = useState("bg-onmount");

This state value will be bound to the className property of the element later on.

In your useEffect() you can set the timer with the amount of time you would want it to be that color, in your case this would be 500ms. After that time, the state value will be updated to the new className which we set to "", so the background color disappears and the component re-renders.

useEffect(() => {
  // set a timer
  const timer = setTimeout(() => {
    setBackgroundClass(""); // set class to none
  }, 500);

  // don't forget to clear in cleanup
  return () => {
    clearTimeout(timer);
  };
}, []);

Don't forget to call clearTimeout() in your cleanup function, this will stop the timer when the component unmounts.

This is how you would bind this value to your element

return (
  <div className={backgroundClass}>
    <p>Some text here</p>
  </div>
);

Try it out in this sandbox

axtck
  • 3,707
  • 2
  • 10
  • 26