Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda