I'm trying to update the state of my component based on key inputs, and pass it to another component.
I can get call keyboardInput() and console.log the correctly when one of the arrow keys are pressed, however I cannot get the returned value to render in <p>The current input is: {this.keyboardInput}</p>
E.g. return {'Y': 1}; when the up key is pressed, but nothing appears in the <p> element
I believe I'm missing some understanding when it comes to the componentWillReceiveProps function, but I'm at a loss.
Could it be that keyboardInput is returning an object not a string value? But even when I change the return to just be a string, I still cannot get it to render.
What am I missing here?
Thanks,
class GameBoard extends Component {
constructor(props) {
super(props);
this.state = {
test: {},
};
}
// Captures event from main window
keyboardInput = (e) => {
const code = e.keyCode ? e.keyCode : e.which;
// Change X and Y values
if (code === 38) { //up key
return {'Y': 1};
} else if (code === 40) { //down key
return {'Y': -1};
} else if (code === 37) { // left key
return {'X': 1};
} else if (code === 39) { // right key
return {'X': -1};
}
};
componentWillMount() {
window.addEventListener('keydown', this.keyboardInput);
}
componentWillUnmount() {
window.removeEventListener('keydown', this.keyboardInput);
}
componentWillReceiveProps(nextProps) {
this.setState.test = this.keyboardInput(nextProps);
}
render() {
return (
<div>
<p>The current input is: {this.keyboardInput}</p>
<Ball/>
</div>
)
}
}
class App extends Component {
render() {
const boardStyle = {
'position': 'absolute',
'backgroundColor': '#7f8c8d',
'height': '100%',
'width': '100%',
};
return (
<div>
<header>
<h1 className="App-title">Welcome to Moving Objects</h1>
</header>
<div style={boardStyle}>
<GameBoard/>
</div>
</div>
);
}
}
export default App;
keyboardInput, as opposed to returning the object into nirvana. (nowhere). You need to 1. look up howsetState()is used 2. do that inside yourkeyboardInput