import React, { Component } from 'react'
class App extends Component {
// The class property proposal
// The state initialization without
// constructor class
state = {msg : 'Hi, There!'}
handleClick(){
// Changing state
this.setState({msg : 'Welcome to the React world!'})
}
render(){
return (
<div>
<h2>Message :</h2>
<p>{this.state.msg}</p>
{/* Set click handler */}
<button onClick={() => this.handleClick()}>
Click here!
</button>
</div>
)
}
}
export default App
Stateful Component
In the code above, the App component has an attribute state which is an object with a msg property. The App component has a handleClick() function which updates the msg property of the state object.
When the App component is rendered, the code renders a div with an h2 and a p element. The h2 element has the message property and the p element has the value of the state.msg property. The handleClick() function is attached to the button element which is the element that is clicked.
0 Comments
Add Comment
Log in to add a comment