BlackDante101
BlackDante101

Reputation: 91

TypeError: Cannot set property 'state' of undefined

I'm a beginner in React JS and I'm trying learn how to work with state and use state in react but I keep getting error cannot set property of state of undefined

import React from 'react';
import './App.css';
import './bootstrap.min.css';

function App() {
  this.state = {
    buttonColor: 'lightgreen'
  }
 
  const changeColor = () => {
    this.setState({buttonColor: this.state.buttonColor = 'lightblue'});
  }
  return (
    <button onClick={()=>changeColor()}  
            style={{ backgroundColor: this.state.buttonColor }} 
            className="btn text-white mt-5 ml-5">
      Change Color
    </button>
  );
}

export default App;

Upvotes: 3

Views: 8243

Answers (1)

ksav
ksav

Reputation: 20821

The above method of setting state would work if you were using a class based react component.

But you are using a functional component, so it does not work.

This is how you could do the same thing with a react function component and the useState hook.

import React, { useState } from "react";

function App() {
  const [buttonColor, setButtonColor] = useState("lightgreen");

  const changeColor = () => setButtonColor("lightblue");

  return (
    <button
      onClick={changeColor}
      style={{ backgroundColor: buttonColor }}
    >
      Change Color
    </button>
  );
}
export default App;

Remember to read the docs

Edit adoring-dew-3g7qc

Upvotes: 6

Related Questions