Creating a dynamic greeter in React, stuck

Hello everyone, I am stuck on my personal project and am hoping that this will only take 5 minutes of someone’s time.
I am trying to create an input where you can enter your name and it will display “hi (name)”
However when I tried the whole app crashed with
TypeError: Cannot read property ‘setState’ of undefined

class NameInput extends Component {
    state = { personsname: null }
    render() { 
        return ( 
            <h1>Hello, please enter your name.</h1>
            <input id="personsname">Your name here</input>
            <button id="namebutton" onClick={setname()} >Enter</button>
            <h1> Hi! {this.state.personsname}</h1>
        </div> );
function setname (){
        this.setState.personsname = document.getElementById('namebutton')

I know something is wrong (probably in the state) but I can’t seem to figure it out.
Thanks in advance for your help.

There are a few things wrong here.

  1. The input element is a void element and should not have content inside it.

  2. Your setname function is outside the class, as such it does not have access to the correct context. Move it inside the class. Now you either have to bind it in the constructor, or you can use one of the other techniques shown on the Handling events page of the React docs. I’d highly suggest reading the docs carefully. It will also show you how you are supposed to use the method in the onClick.

  3. setState is a method, read Using State Correctly.

  4. document.getElementById('namebutton') is the button element, you want the input element value.

1 Like

I couldn’t ask for a better opinion. Thank you.