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;
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;
Share
Improve this question
edited Dec 22, 2020 at 10:37
Software Engineer
16.1k8 gold badges84 silver badges107 bronze badges
asked Nov 19, 2020 at 21:12
BlackDante101BlackDante101
912 silver badges9 bronze badges
2
- 3 Are you trying to make a function ponent or a class ponent? Your issue is basically that you're mixing the syntaxes of them. – Nicholas Tower Commented Nov 19, 2020 at 21:14
- reactjs/docs/hooks-state.html – Brian Thompson Commented Nov 19, 2020 at 21:14
1 Answer
Reset to default 6The above method of setting state would work if you were using a class based react ponent.
But you are using a functional ponent, so it does not work.
This is how you could do the same thing with a react function ponent 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