2

I am new to react js. I am trying to rotate an image by clicking an arrow key. Someone help me out and also share some documentation for learning react js.

Thanks in advance.

My code

.js

import React from 'react';
import Ballimg from '../Image/ImageMovement.gif'
import Style from '../Style/ImageComponentStyle.module.css'

class Ball extends React.Component{
    constructor(props){
        super(props);
        this.handleKeyDown = this.handleKeyDown.bind(this)
        this.state = {
            imageDirection: Style.right
        };
    }
    handleKeyDown(e){
        if(e.KeyCode === 37){
            this.setState({imageDirection : Style.left})
        }
        else if(e.KeyCode === 38){
            this.setState({imageDirection : Style.up})
        }
        else if(e.KeyCode === 39){
            this.setState({imageDirection : Style.right})
        }
        else if(e.KeyCode === 40){
            this.setState({imageDirection : Style.down})
        }
    }
    render(){
        return(
            <div>
                <img src={Ballimg} alt="ball movement" className={this.state.imageDirection} onKeyDown={this.handleKeyDown}/>
            </div>
        );   
    }
}
export default Ball;

.module.css

.down {
    transform: rotate(90deg);
}
.left {
    transform: rotate(180deg);
}
.up {
    transform: rotate(-90deg);
}
.right{
    transform: rotate(0deg);
}
Nivedh
  • 120
  • 13

2 Answers2

0

First, you have a typo:

// Not e.KeyCode
e.keyCode === 37

Then, you might want to set a global listener for keyDown or the event will only work when the element is focused:

window.addEventListener('keydown', e => { 
  //e.keyCode
});

Full hooks example:

const App = () => {
  const [direction, setDirection] = useState(0);

  useEffect(() => {
    window.addEventListener('keydown', e => {
      if (e.keyCode === 37) {
        setDirection(180);
      } else if (e.keyCode === 38) {
        setDirection(-90);
      } else if (e.keyCode === 39) {
        setDirection(0);
      } else if (e.keyCode === 40) {
        setDirection(90);
      }
    });
  }, []);

  return (
    <img
      style={{ transform: `rotate(${direction}deg)` }}
      alt="cat"
      src={image}
    />
  );
};

Edit Q-60901940-KeyDownExample

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
-1

Since you have not used public class method, you can call the method just like this:

onKeyDown={handleKeyDown}

The method binding with this is required to bind this. So, if you use onKeyDown={this.handleKeyDown}, you have to bind like:

this.handleKeyDown = this.handleKeyDown.bind(this) // inside constructor

Or, using public class method:

handleKeyDown = (e) => {}

For more details, I suggest you to read my another answer.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231