howranwin
howranwin

Reputation: 164

ReactJS how to apply transitions to inline stylings in react?

I'm currently working on a responsive navbar for my site using react, and I'm toggling the navbar with a state to check if the menu was toggled on or off. When it's on, it'll apply to the div a style of transform: translateX(0%), else it's transform: translateX(100%). When it's transform: translateX(100%), the div is just completely off the screen. When I toggle the menu, it just appears suddenly, and I'm not sure why the transition property doesn't work.

In Header.js

{this.state.showMenu ? (
  <div
   className="header__menu"
   style={this.showMenu ? null : { transform: "translateX(100%)" }}
  ></div> : null }

In Header.css

.header__menu {
  position: absolute;
  top: 0;
  right: 0;
  background-color: white;
  outline: 1px solid var(--border-accent);
  padding: 64px 12px 0 12px;
  height: 100vh;
  width: 220px;
  z-index: 9;
  transform: translateX(0%);
  transition: transform 0.5s ease-in-out;
}

The expected behavior, if the transition worked, is for the navbar to slide-in rather than just appear suddenly. Is there a way for me to apply the transition to the inline styling I have in the Header.js file?

Upvotes: 1

Views: 795

Answers (2)

vipcxj
vipcxj

Reputation: 1038

You use the wrong css.

The translateX is the state, not the animation. Use animation instead.

@keyframes menu-open {
  from {width: 0px;}
  to {width: 220px;}
}

.open {
  animation-name: menu-open;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

@keyframes menu-close {
  from {width: 220px;}
  to {width: 0px;}
}

.close {
  animation-name: menu-close;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

.header__menu {
  position: absolute;
  top: 0;
  right: 0;
  background-color: black;
  outline: 1px solid var(--border-accent);
  padding: 64px 12px 0 12px;
  height: 100vh;
  z-index: 9;
}
import cs from 'classnames';
import React from "react";
import "./styles.css";

export default function App() {
  const [showMenu, setShowMenu] = React.useState(false);
  const onClick = React.useCallback(() => {
    setShowMenu(!showMenu);
  }, [showMenu]);
  const classnames = cs('header__menu', {
    open: showMenu,
    close: !showMenu,
  })
  return (
    <div className="App">
      <button onClick={onClick}>{showMenu ? "close" : "open"}</button>
      {<div className={classnames} />}
    </div>
  );
}

Here is the working codesandbox

Upvotes: 1

Konstantin Samarin
Konstantin Samarin

Reputation: 857

You should specify both transform properties in style attribute like so: style={{transform: this.showMenu ? "translateX(0%)" : "translateX(100%)"}}

Upvotes: 0

Related Questions