Skip to content
Advertisement

React Class Component setState undefined

I am attempting to update a variable from “” to a string of text with an onClick method in React. I’ve approached this several different ways following examples on the web and Youtube but all are resulting in various error messages.

This is the latest attempt and I’m receiving an error message that it cannot set properties of undefined setting set state & it’ pointing to the line that reads “super(props).

Can you please let me know what is wrong with this approach?

import React,{Component} from "react";

//Declaring variable globally as I was receiving error messages previously
let response = "";

class Track extends Component{
        constructor(props) {
        super(props)

        //Setting the initial state
        this.state = {
         response: "",
          
        };
    }
    
    //Not sure why I'm adding this as some tutorials did not have this but nothing else was working and I came across one with this so I'm attempting it.
    componentDidMount(){
        response = "";
    }
//This function takes the variable from "" and updates it to the string below
    autoResponse(){
    this.setState=({response : "This is not a valid tracking #"})
 }
     
    render(){  
     
    return(<>
   
<input placeholder="Enter Tracking #"></input>

<button onClick={this.autoResponse}>TRACK</button> {/*This is for the setState function. I tried preventDefault() but it stated it's not defined*/}
<div className="response-cntr">
    <p className="response-text">{this.state.response}</p> {/*Should display the updated variable after the onClick*/}
</div>


        </>)
    }

}

export default Track;

Advertisement

Answer

  1. You do not need the global variable response.
  2. No need for the componentDidMount either, you already set the initial state in the constructor.
  3. setState is a function, so you need to call it and not assign something to it
  4. use an arrow function for the autoResponse, if you intend to pass it as a prop to other components, so that it retains the correct this.

import React, {
  Component
} from "react";

class Track extends Component {
  constructor(props) {
    super(props);

    //Setting the initial state
    this.state = {
      response: ""
    };
  }

  autoResponse = () => {
    this.setState({
      response: "This is not a valid tracking #"
    });
  }

  render() {
    return (<>
      <input placeholder="Enter Tracking #"></input>
      <button onClick={this.autoResponse}>TRACK</button>
      <div className="response-cntr">
        <p className="response-text">{this.state.response}</p>
      </div>
     </>);
    }
  }

  export default Track;
Advertisement