Jump to content
Search Community

How to get this flip animation working in react using useGSAP

wayz test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Which file should we be looking at? You are sharing the file styles.css, which of course does not have any GSAP code. 

 

When sharing a Stackblitz link, please include in which file we should be looking for the GSAP code you've wrote.

Link to comment
Share on other sites

  • Solution

Hi,

 

There are a few issues with your demo, the one that causes the biggest problem is this:

.event-1[data-grid='img-1'] {
  grid-area: img-1;
  /* z-index: 1; */
  cursor: default;
}

.event-2[data-grid='img-2'] {
  grid-area: img-2;
}

.event-3[data-grid='img-2'] {
  grid-area: img-3;
}

.event-4[data-grid='img-4'] {
  grid-area: img-4;
}

With those styles the grid will only work only for those specific classes. As soon as you change the dataset value for the main image and the click target those classes won't work anymore. It has to be like this:

.event[data-grid='img-1'] {
  grid-area: img-1;
  /* z-index: 1; */
  cursor: default;
}

.event[data-grid='img-2'] {
  grid-area: img-2;
}

.event[data-grid='img-2'] {
  grid-area: img-3;
}

.event[data-grid='img-4'] {
  grid-area: img-4;
}

Then your code is being created before the elements are rendered in the DOM when you do this:

let events = gsap.utils.toArray(".event");
let active = events[0];
events.forEach(el => {
  el.addEventListener("click", () => changeGrid(el));
});
function changeGrid(el) {
  if (el === active) return;
  let state = Flip.getState(events);
  active.dataset.grid = el.dataset.grid;
  el.dataset.grid = "img-1";
  active = el;
  // Flip.from(state, {
  //     duration: 0.3,
  //     absolute: true,
  //     ease: "power1.inOut"
  // });
}

Running this code in the global scope of a React component will execute before the return statement that actually renders the elements on the DOM, so the events variable is just an empty array, so nothing will happen. In react you have to use effect hooks for that in order to ensure that the elements are rendered in the DOM. We have a useGSAP hook that simplifies this quite a bit:

https://gsap.com/resources/React

 

Here is a port of that particular demo in React:

https://stackblitz.com/edit/react-w54qpa

 

Finally I strongly recommend you to read and practice more about React, since the problems you had are not GSAP related, but more related with HTM/CSS/JS and the way react works.

 

Hopefully this helps.

Happy Tweening!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...