What is event?
Events are actions or occurrence that happen in the system you are programming, which the system teels you system tells you about so your code can react to them.
Most often user of a website generates events.
REACT EVENTS:-
Just like html DOM events react can perform actions based on user events.
React has the same events as HTML : click ,change,mouseover,etc.
EVENT WITH FUNCTION COMPONENT
function App() { function Hello(){ alert("hello everyone") } return ( <div> <input type="button" value="click" onClick={Hello}/> </div> ) } export default App;
EVENT WITH CLASS COMPONENT
we can call function with
this
keyword.export default class User extends Component { HelloAnku(){ alert("hello ankuuuu") } render() { return ( <div> <input type="button" value="click" onClick={this.HelloAnku} /> </div> ) } }
Adding Events
React events are written in
camelCase
syntx:onClick
instead ofonclick
.React event handlers are written inside curly braces.
onClick={apply}
instead ofonclick="apply()"
.
Passing arguments
To pass an argument to the
function App() {
const Hello = (name) => {
alert("hello " + name);
}
return (
<div>
<input type="button" value="click" onClick={ () => Hello("everyone")}/>
</div>
)
}
export default App;
Passing arguments as a props
With function component
function User(props) {
const Hello = (name) => {
alert("hello " + name);
}
return (
<div>
<input type="button" value="click" onClick={ () => Hello(props.name)}/>
</div>
)
}
export default User;
With class component
we have declare function hello
in render function so we can not usethis
keyword for calling the function.
export default class User extends Component {
render() {
const Hello = (name) =>{
alert("hello " + name);
}
return (
<div>
<input type="button" value="click" onClick={() => Hello(this.props.name)} />
</div>
)
}
}
BINDING EVENT HANDLERS
- In reactjs we need to bind events so that the this keyword would not return an "undefined".
import React, { Component } from 'react'
export default class User extends Component {
constructor () {
super();
this.HandleEvent = this.HandleEvent.bind(this);
this.state = {
name: "hello"
}
}
HandleEvent(){
this.setState({
name:"heyy"
});
}
render() {
return (
<div>
<h1>{this.state.name}</h1>
<button type='click' onClick={this.HandleEvent}>click</button>
</div>
)
}
}
BINDING EVENT HANDLER IN RENDER METHOD
We can bind the handler when it is called in the render method using bind() method.
export default class User extends Component {
constructor () {
super();
this.state = {
name: "hello"
}
}
HandleEvent(){
this.setState({
name:"heyy"
});
}
render() {
return (
<div>
<h1>{this.state.name}</h1>
<button type='click' onClick={this.HandleEvent.bind(this)}> click</button>
</div>
)
}
}
Haapy learning...