Jump to content
Search Community

onMouseEnter and Leave on the array in React

Arahis test
Moderator Tag

Recommended Posts

Hi! I'm working with React and can't resolve an issue. I'm getting array of objects from API and show them using .map(). I need to display the Title of the picture when hovering the Section with that picture. Now I'm only getting the title of the last picture when hovering each of sections.

See the Pen bGgqXdG by Arahis (@Arahis) on CodePen

Link to comment
Share on other sites

Hi and welcome to the GreenSock forums.

 

The problem in your sample is that in the useEffect hook you're assigning the GSAP instance to the titleStyleRef.current value on every loop, so basically you're doing that three times and of course the final one will be the reference there. Also you don't need to use a forEach loop, since you can use an array.map() method to return the new array. This code seems to be doing what you're after:

function App() {
  const titleRef = useRef([]);
  const titleStyleRef = useRef([]);

  const addTitlesToRef = (el) => {
    if (el && !titleRef.current.includes(el)) {
      titleRef.current.push(el);
    }
  };

  useEffect(() => {
    titleStyleRef.current = titleRef.current.map((title, index) => {
      return gsap.to(title, {
        duration: 1,
        opacity: 1,
        paused: true,
        ease: "power3"
      });
    });
  }, []);
  
  return (/* JSX HERE */);
};

Also don't forget to pass an array with dependencies in the useEffect hook, otherwise that code will run every time your component's state is updated.

 

Happy Tweening!!!

  • Like 2
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...