I am new to react and It didn’t work onclick event why in my index.js it show the paragraph and the button is clickable but it doesn’t change the value.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Car extends React.Component{
constructor(props){
super(props);
this.state = {color: "Red",
model: "Mustang"}
}
changeColor = () => {
this.setState = ({color: "Green"});
}
render(){
return (<><p>I have a {this.state.model} car color {this.state.color}</p>
<button type="button" onClick={this.changeColor}>Click Me</button></>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car/>);
this.setState
is a function you need to call, not a variable that needs to be assigned. Here is the legacy guide for event handling in React prior to the introduction of functional components.
Note: I used <React.Fragment>
instead of the short-hand <>
in the examples below, because the version of Babel that Stack Overflow uses is too old. Feel free to change the fragment back to the short-hand.
class Car extends React.Component {
constructor(props){
super(props);
this.state = { color: "Red", model: "Mustang" };
this.changeColor = this.changeColor.bind(this); // Required
}
changeColor() {
this.setState({ color: "Green" }); // Call setState
}
render() {
return (
<React.Fragment>
<p>I have a {this.state.model} car color {this.state.color}</p>
<button type="button" onClick={this.changeColor}>Click Me</button>
</React.Fragment>
)
}
}
ReactDOM.createRoot(document.getElementById("root")).render(<Car />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
You should checkout functional components and hooks. This is the new way to write React code starting in React 17/18.
const { useCallback, useEffect, useState } = React;
const Car = () => {
const [color, setColor] = useState('Red');
const [model, setModel] = useState('Mustang');
const changeColor = useCallback(() => {
setColor('Green');
}, []);
return (
<React.Fragment>
<p>I have a {model} car color {color}</p>
<button type="button" onClick={changeColor}>Click Me</button>
</React.Fragment>
)
}
ReactDOM.createRoot(document.getElementById("root")).render(<Car />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
You are using a very old React style. Consider reworking this using React Hooks.
Stack Overflow trouble question title.
Please see How to Ask. Present your issue before you throw code at us, and consider setting your spell checker to English.