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

138
Views
Moving a component with arrow keys in React

I'm learning react and I'm experimenting with the code, yesterday I wanted to make a ball that moves when arrow keys are pressed, I saw some tutorials and made it with js, very easy, then I wanted to make it with react but the problem I had is that I didn't know where to start, I only made a Ball component with the height,weight ecc., but I didn't Know how to access this component and interact with him or track where the component is at the moment (for example in the javascript scratch I did, I could place a function that was like "when the ball reaches left: 40 show me a message), So the problem is that I don't know if this logic (like the one for moving it with arrow keys should be placed inside the Ball component or maybe in the app component that renders the Ball component) I'll put the code of the js to make you see what I wanted to translate in React.

HTML

<body>
    <div class="circle" id="circle"></div>
    <script src="script.js"></script>
  </body> 

CSS

   .circle{
    height: 100px;
    width: 100px;
    border-radius: 50%;
    background-color: purple;
}

JS

let circle = document.querySelector(".circle");
let circleID = document.getElementById("circle");
let moveBy = 10;

window.addEventListener("load", () => {
  circleID.style.position = "absolute";
  circleID.style.left = 0;
  circleID.style.top = 0;
});

window.addEventListener("keydown", (e) => {
  switch (e.key) {
    case "ArrowLeft":
      circle.style.left = parseInt(circle.style.left) - moveBy + "px";
      if (circleID.style.left == "40px") {
        console.log("40px reached");
      }
      break;
    case "ArrowRight":
      circle.style.left = parseInt(circle.style.left) + moveBy + "px";
      break;
    case "ArrowUp":
      circle.style.top = parseInt(circle.style.top) - moveBy + "px";
      break;
    case "ArrowDown":
      circle.style.top = parseInt(circle.style.top) + moveBy + "px";
      break;
  }
});

Thank you all for the attention and have a good day!

about 4 years ago · Juan Pablo Isaza
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!