I'm trying to recreate this effect: https://imgur.com/a/4iu2ScT Currently I'm rendering an with the "src" based on the state. Like this
import React from "react";
import styled from "styled-components";
import home_food from "../images/home/home_aji_de_gallina.jpg"
import food from "../images/menu/entry/causa.jpeg"
import { useState } from "react";
const TestBoks = styled.div`
background-color:red;
width: 30px;
height: 30px;
opacity: ${props => props.opacity || 0.6};
transition: ease-in-out;
`;
const TestContainer = styled.div`
display: flex;
width: 100%;
justify-content: space-around;
`;
const WholePage = styled.div`
height: 100vh;
width: 100%;
img{
width: 100px;
transition: ease-in;
}
`
const pictures = [home_food,food]
const Test = () => {
const [Picture, setPicture] = useState(pictures[0])
function setNewPicture(index_number){
setPicture(pictures[index_number])
}
return (
<WholePage>
<TestContainer>
<TestBoks key={Picture[0]} onMouseEnter={() => setNewPicture(0)}/>
<TestBoks key={Picture[1]} onMouseEnter={() => setNewPicture(1)}/>
</TestContainer>
<img src={Picture} alt="ononon" />
</WholePage>
);
};
export default Test;
And it ends up looking like this: https://imgur.com/a/bTJLTAC
However, it ignores the animation I described in the styled.div
So my question is, how do i trigger an css animation on a render caused by a state change?
If there is a better way to achieve the effect linked in the Imgur, please share that as well
You should use useEffect in order to listen for state changes. see: https://reactjs.org/docs/hooks-effect.html
Also, don't forget to import: import { useEffect } from 'react';
const Test = () => {
const [Picture, setPicture] = useState(pictures[0])
const [newPicture, setNewPicture] = useState(0)
useEffect(() => {
setPicture(pictures[newPicture])
}, [newPicture]);
return (
<WholePage>
<TestContainer>
<TestBoks key={Picture[0]} onMouseEnter={() => setNewPicture(0)}/>
<TestBoks key={Picture[1]} onMouseEnter={() => setNewPicture(1)}/>
</TestContainer>
<img src={Picture} alt="ononon" />
</WholePage>
);
};