React Event Handling
* An event is an action that could be triggered as a result
of the user action (or) system generated event.
* For example, a mouse click,loading of a web page,
pressing a key,window resizes, and other interactions are called Events.
* React events are named using camelCase, rather than
lowercase.
* In React, with help of JSX you pass a function as the
event handler, rather than a string.
onClick = {shoot} instead of onClick=”shoot()”
Possible way of Event Handling
* Using the event method in class component.
* Using bind keyword in event.
* Passing arguments to event using arrow function
* Passing arguments to event using bind.
Event Handling Using Arrow
Function
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
class Eventbind extends React.Component{
constructor(){
super()
this.state={
msg:"Welcome"
}
}
clickEvent=()=>{
this.setState({
msg:"Thank
you"
})
}
render(){
return(
<div>
<h1>{this.state.msg}</h1>
<button onClick={this.clickEvent}>Click</button>
</div>
)
}
}
var mystyle={color:'green',textAlign:'center'}
const element =<div style={mystyle}><Eventbind/></div>;
root.render(element);
Output
Passing Argument to Event Handling
Creating anonymous function->without giving function name is called Anonymous
function.
Changes in index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
class Eventbind extends React.Component{
constructor(){
super()
this.state={
msg:"Welcome"
}
}
clickEvent=(a)=>{
this.setState({
msg:a
})
}
render(){
return(
<div>
<h1>{this.state.msg}</h1>
<button onClick={()=>this.clickEvent("Hello World")}>Click</button>
</div>
)
}
}
var mystyle={color:'green',textAlign:'center'}
const element =<div style={mystyle}><Eventbind/></div>;
root.render(element);
Output
No comments:
Post a Comment