Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Using React-Spring useSprings only on active button in array

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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%;
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!