I am trying to animate a position change of the active box. When the user clicks on the box, I would like the box to animate a margin-top change and the rest of the boxes to stay at 0px. When the user changes the active box, the previously active box will return to 0px and the new active box will acquire a margin-top of 50px.
I think I am nearly there but I haven't quite managed to get it to work yet. I would be really grateful if someone could help enlighten me as to what I am doing wrong.
import { useSpring, useSprings, animated } from "react-spring";
import styled from "styled-components";
const Nav = () => {
// Set Active Box
const [activeBox, setActiveBox] = useState(0);
const handleClick = (index) => {
setActiveBox(index);
};
// Boxes
const boxes = [box1, box2, box3, box4];
// useSprings
const springs = useSprings(
boxes.length,
boxes.map((box, index) => ({
marginTop: activeBox === index ? 50 : 0,
}))
);
return (
<NavContainer>
{springs.map((prop, index) => (
<StyledBox
style={prop}
key={index}
onClick={() => handleClick(index)}
currentActiveBox={activeBox === index}
>
<img src={boxes[index]} alt="" />
</StyledBox>
))}
</NavContainer>
);
};
export default Nav;
const NavContainer = styled.div`
position: absolute;
bottom: 0;
width: 200px;
height: 75px;
`;
const StyledBox = styled.div`
width: 25px;
height: 25px;
img {
width: 100%;
height: 100%;
}
`;
Thank you!
The issue was that animated was not added to the styled component!
const StyledBox = styled(animated.div)`
width: 25px;
height: 25px;
img {
width: 100%;
height: 100%;
}