Search code examples
cssreactjscss-transitionscss-transforms

React and CSS: Timing function is not executed correctly


React and CSS make nothing but problems in my experience. The child-section Todo is supposed to smoothly transition to the side, out of bounds. Instead, it just happens immediately. What to change?

.container {
  position: relative;
  overflow: hidden;
}

.todo {
  background: var(--geist-background);
  padding: 2rem;
  position: relative; /* For the left property to work*/
  transition: transform 3s ease-in;
  transform: translateX(0%);
}

.todo-slide-out {
  position: relative; /* For the left property to work*/
  transform: translateX(100%);
}
        <div className="container">
            <h1>Move along now</h1>
            <div className={view ? "todo" : "todo-slide-out"}>
                <div className="attributes">
                    <h1>{hardTodo.title}</h1>
                    <p>{hardTodo.content}</p>
                </div>           
                <div className="actions">
                    <button onClick={() => deleteTodo()}>Delete Todo</button>
                </div>    
            </div>
        </div> 

Code Sandbox: https://codesandbox.io/s/nice-shannon-hyhfj9?file=/src/index.js


Solution

  • (Posting my comment as an answer):

    • Your .todo-slide-out should extend the .todo CSS rule instead of being a separate style entirely.
      • Change the selector from .todo-slide-out to .todo.slide-out.
      • Change your JSX to <div className={view ? "todo" : "todo slide-out"}> (note the space).
    • Also, you don't need position: relative; if you aren't using position: absolute and top/left/bottom/left. The position: relative; property is not necessary to use transform:.
      • You also don't need transform: translateX(0%); in .todo {} either.
    .todo {
      background: var(--geist-background);
      padding: 2rem;
      transition: transform 3s ease-in;
    }
    
    .todo.slide-out {
      transform: translateX(100%);
    }
    
            <div className="container">
                <h1>Move along now</h1>
                <div className={view ? "todo" : "todo slide-out"}> <!-- Was "todo-slide-out" but is now "todo slide-out" which corresponds to the ".todo.slide-out" selector. -->
                    <div className="attributes">
                        <h1>{hardTodo.title}</h1>
                        <p>{hardTodo.content}</p>
                    </div>           
                    <div className="actions">
                        <button onClick={() => deleteTodo()}>Delete Todo</button>
                    </div>    
                </div>
            </div>