Here, I will explain how to bind state value & how to set or change state value.
Now I am creating component with name Car and create one object in constructor with keys like brand, model, color and year and stored value in state.
Next,I am binding all state value in HTML and also adding button with one function for change state value, when user click on change color button it will change color state value.
Now I am creating component with name Car and create one object in constructor with keys like brand, model, color and year and stored value in state.
Next,I am binding all state value in HTML and also adding button with one function for change state value, when user click on change color button it will change color state value.
import React from 'react'; import ReactDOM from 'react-dom'; class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } changeColor = () => { this.setState({color: "blue"}); } render() { return ( <div> <p> I have {this.state.color} color { this.state.model} car with {this.state.year} model. </p> <button type="button" onClick={this.changeColor}>Change color</button> </div> ); } } ReactDOM.render(<Car/>, document.getElementById('root'));
Output: Before button click : I have red color Mustang car with 1964 model. After button click : I have blue color Mustang car with 1964 model.
Comments
Post a Comment