I created a small reproduction of my code with which i have an issue. I wanted to create a functionality of small square element (.box)
sliding to the center of selected answer. Currently its sliding wrong as its going completely different direction than it should. I assume i would need to use commented line // const boxRect = box.getBoundingClientRect();
and play with its position but tried several times without success.
The important thing is that the first slide must start from .box
initial position defined in css. Then it should just change its position between selected answers.
const { useRef } = React;
const ANSWERS = ["answer 1", "answer 2", "answer 3", "answer 4"];
const App = () => {
const boxRef = useRef(null);
const handleSelectAnswer = (answer) => {
const selectedAnswerElement = document.querySelector(
`[data-answer="${answer}"]`
);
const box = boxRef.current;
const answersContainer = document.querySelector(".answers");
if (selectedAnswerElement && box && answersContainer) {
const selectedAnswerRect = selectedAnswerElement.getBoundingClientRect();
const containerRect = answersContainer.getBoundingClientRect();
// const boxRect = box.getBoundingClientRect();
const offsetX =
selectedAnswerRect.left -
containerRect.left +
selectedAnswerRect.width / 2;
const offsetY =
selectedAnswerRect.top -
containerRect.top +
selectedAnswerRect.height / 2;
box.style.transform = `translate(${offsetX}px, ${offsetY}px)`;
}
};
return (
<div className="answers">
{ANSWERS.map((answer) => (
<button
key={answer}
data-answer={answer}
onClick={() => handleSelectAnswer(answer)}
>
{answer}
</button>
))}
<div className="box" ref={boxRef} />
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
.answers {
margin: 0 auto;
display: grid;
grid-template-columns: repeat(2, 270px);
grid-template-rows: repeat(2, 1fr);
column-gap: 1rem;
row-gap: 1rem;
color: white;
position: relative;
width: max-content;
}
.answers button {
height: 150px;
}
.box {
width: 50px;
height: 50px;
background-color: lightblue;
position: absolute;
bottom: -25%;
left: 0;
right: 0;
margin: 0 auto;
transition: all 0.5s ease;
z-index: 999;
}
<div id="root">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script>
</div>
2
Answers
I have removed default left, right and bottom css from your box elements so it will not cause any issue in dynamic position property in js and Also I have used state to store the x and y position of box element.
Please check updated below code.
Let me know if it works for you or not.
You can compute the position using JS, but then you probably want to use CSS handle everything else, by setting CSS variables: