States in React:-
States are the built in object for React components. They are generally
compatible with class based components. For using state with Functional
components we make use of Hooks.
The state object is used to store all the data that belongs to the components.
The state is only accessible inside the component it belongs to.
State is mutable, it can be changed as per the component is re-rendered.
To use state inside a class component we make use of “this.state”.
To use state inside a functional component we make use of “useState”.
Handling Events in React.
Q: What are events?
A: Events are response that are given as a reply to the user by browser.
Note: Handling events in Functional components and class based component is
having a little difference.
#Handling events in Functional Components:
function First(){
function Myfun(){
alert('This is a funtional component')
}
return(
<>
<h1>Event Handling in functional component</h1>
<button onClick={Myfun}>Click Me</button>
</>
);
}
export default First;
#Handling Events in Class based Components:
import React from 'react'
class Second extends React.Component{
Myfun(){
alert('This is a class based component')
}
render(){
return(
<>
<h1>Event Handling in Class Based component</h1>
<button onClick={this.Myfun}>Click Me</button>
</>
);
}
}
export default Second;
Basic example of changing the states in class based components
import React from 'react';
class Second extends React.Component{
constructor(){
super()
this.state={
msg:"Please Subscribe"
}
}
changeMessage(){
this.setState({
msg:"Thanks for subscribing"
})
render(){
return(
<>
<h1>{this.state.msg}</h1>
<button
onClick={()=>this.changeMessage()}>Subscribe</button>
</>
);
}
}
export default Second;