Reputation: 91
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
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
Upvotes: 6