Home > Enterprise >  Name of button won't change with setState
Name of button won't change with setState

Time:01-13

I am begining learning React. I am following along to a tutorial video, and when I press the button, the name should change from Juju to Julie. But when I press the button, the name doesn't change. I keep comparing the code to the code I see in the video and it seems identical.
Please bear with me, I am trying to learn React and I am at the very beginning, I just cant figure out why the name won't change. Here is my App.js code:

import { Component } from "react";

import logo from "./logo.svg";
import "./App.css";

class App extends Component {
constructor() {
  super();

  this.state = {
    name: "Juju",
  };
}

render() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Hi {this.state.name}</p>
        <button
          onclick={() => {
            this.setState({ name: "Julie" });
          }}
        >
          Change name
        </button>
      </header>
    </div>
  );
}
}

export default App;

CodePudding user response:

The event you have used should be onClick. Please try the followed code.

    <button onClick={() => {this.setState({ name: "Julie" }) }} >
      Change name
    </button>

CodePudding user response:

If you check the console you can see this error:

react-dom.development.js:86 Warning: Invalid event handler property `onclick`. Did you mean `onClick`?
    at button
    at header
    at div
    at App (http://localhost:3000/static/js/bundle.js:29:5)

Make sure to check the console to see if you are getting any errors.

  • Related