How can I change the value of state.message?

I’ve known that I can press “enter” key to show “You pressed the enter key!” because the keycode of enter is equal to 13. So my first question is that how I can show “Raymond You pressed the enter key!” as the state.message = “”, how can I change it to what I want? And my second question is what the usage of componentWillUnmount is in this challenge, can you give me some specific details? Thanks!

  **Your code so far**

class MyComponent extends React.Component {
constructor(props) {
  this.state = {
    message: ''
  this.handleEnter = this.handleEnter.bind(this);
  this.handleKeyPress = this.handleKeyPress.bind(this);
// Change code below this line
componentDidMount() {
  document.addEventListener("keydown", this.handleKeyPress)

componentWillUnmount() {
  document.removeEventListener("keydown", this.handleKeyPress)

// Change code above this line
handleEnter() {
  this.setState((state) => ({
    message: state.message + 'You pressed the enter key! '
handleKeyPress(event) {
  if (event.keyCode === 13) {
render() {
  return (
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Add Event Listeners

Link to the challenge:

Google “react onChange event”

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