EKC826
EKC826

Reputation: 19

React.js - move component when button is clicked

I am pretty new to react and have a question on how to do some relatively simple animations.

I have two buttons and an arrow in the middle. What I want is when a button is clicked to have the arrow move to under that button. Can this be done with NPM plugins or is javascript involved. Any help would be greatly appreciated.

Happy Coding!

Upvotes: 0

Views: 1124

Answers (2)

Franco Gabriel
Franco Gabriel

Reputation: 568

You can achieve it with simple CSS and some React, I attached an example of how to do that with simple CSS animations. As an example its intended to show you some case and the logic behind it for you to research further in your convenience and requirements. Hope it helps!

const {useState} = React;

const App = () => {
  const [selectedButton, setSelectedButton] = useState(0)

  return (
    <div>
      <button
        onClick={() => setSelectedButton(0)}
      >
        Button #1
      </button>
      <button
        onClick={() => setSelectedButton(1)}
      >
        Button #2
      </button>
      <div 
        className={`arrow ${selectedButton === 0 ? 'first' : 'second'}`}
      >
        ↑
      </div>
    </div>
    );
};

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);
.arrow {
  width: 73px; /* Button width */
  text-align: center;
}

.arrow.first {
  animation: moveLeft .3s ease forwards;
}

.arrow.second {
  animation: moveRight .3s ease forwards;
}

@keyframes moveRight {
  0% {
    transform: translateX(0)
  }
  100% {
    transform: translateX(73px)
  }
}

@keyframes moveLeft {
  0% {
    transform: translateX(73px)
  }
  100% {
    transform: translateX(0)
  }
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Upvotes: 1

You can check this link, https://github.com/FormidableLabs/react-animations

npm install --save react-animations

Upvotes: 0

Related Questions