I have this code:
import React, { Component } from "react"; export default class Safe extends Component { constructor(props) { super(props); this.state = { userInput: "", password: 1234 } } keyClicked = (evt) => { // HERE!! } render() { return ( <div className="safe"> <div className="display">{this.state.userInput}</div> <div className="keypad"> {Array.from({length: 9}, (x, key) => <button className="key" key={key++} onClick={this.keyClicked}>{key++}</button>)} </div> </div> ) } }
I am attempting to make a “safe” with a number pad. In order to open the safe, the user must enter a specific code in order to “open it”.
Currently, I am working on showing what the user has input through the number pad onto the display. However, I am unsure on how to get what number the user has inputted through the number pad. I have put a comment saying “HERE!!” to show where I want to access the inputted number.
I have attempted to use evt.target.value
but when I try to console.log()
the evt
, it shows up as an empty string.
Any help is appreciated as I’m new to React!
Advertisement
Answer
I think that for this case is better to use map()
. And declare the array beforehand. This way it’s possible to pass the number clicked as an argument to the click handler.
Try the following:
export default class Safe extends Component { constructor(props) { super(props); this.state = { userInput: "", password: 1234 }; } numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; handleClick = (n) => { console.log(n) } render() { return ( <div className="safe"> <div className="display">{this.state.userInput}</div> <div className="keypad"> {this.numbers.map((number, i) => { return ( <button className="key" key={i} onClick={() => this.handleClick(number)} > {number} </button> ) })} </div> </div> ) } }