Key press will not render value to the display

Tell us what’s happening:
Hi,
Sorry to bother everyone. I found some relaxation time for the coding problem solving :slight_smile: and was wondering if someone could help me with following problem:

Method ‘setDisplay’ should take value from event listener and set state.tempcount to this value.

tempcount should then be rendered to the screen within div with id=‘display’.

Nothing happens when I press button number on the calculator.

Kindly ask for help.

Many thanks.

Your code so far

const digits = [
  ["zero", 0],
  ["one", 1],
  ["two", 2],
  ["three", 3],
  ["four", 4],
  ["five", 5],
  ["six", 6],
  ["seven", 7],
  ["eight", 8],
  ["nine", 9]
];
const operators = [
  ["add", "+"],
  ["subtract", "-"],
  ["multiply", "*"],
  ["divide", "/"],
  ["decimal", "."],
  ["equals", "="],
  ["clear", "AC"]
];




class Calculator extends React.Component {
  constructor(props){
    super(props);
    this.state={
      count:0,
      tempcount:0
    };
    
    this.setDisplay=this.setDisplay.bind(this);
  };
  
  // take value from the calculator and pass it to setDispley
  componentDidMount() {
    document.addEventListener('keydown',this.setDisplay)
  }
  
  componentWillUnmount(){
    document.removeEventListener('keydown',this.setDisplay)
  }
  
  
  // take value from the event listener and set state.tempcount to this value.
  //tempcount should then be rendered to the screen within div with id='display'
  setDisplay=(e)=>{
     this.setState({
      tempcount:e
    });
  
  }
  
  

  render() {
    //render numbers to the screen
    const padDigits = digits.map((arr, num, dig) => {
     // console.log(arr[0], num);
      return (
        <button id={arr[0]} className="buttons">
          {num}
        </button>
      );
    });

    //render operators to the screen
    const padOperators = operators.map((arr, oper, arrArr) => {
      return (
        <button id={arr[0]} className="buttons">
          {arr[1]}
        </button>
      );
    });
    return (
      <div id="container">
        <div id="display">{this.state.tempcount}</div>
        <div id="digits">
          {padDigits}
        </div>
        <div id="operators">{padOperators}</div>
      </div>
    );
  }
}

ReactDOM.render(<Calculator />, document.getElementById("App"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Build a JavaScript Calculator

Link to the challenge:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.