ReactJs Tutorials
Events in React
An event is an action that perform a result of the user action or system generated event. React has the same events as javascript: mouse click, change, mouseover, pressing a key, window resizes are called events.
React has its own event handling system which is very similar to handling events on DOM elements. React events are written in camelCase. such as onClick instead of onclick
React event handlers are written inside curly braces { }
File name : index.php
React events are named as camelCase instead of lowercase.
With JSX, a function is passed as the event handler instead of a string.
<button onClick={show}>Click me!</button>
Example
File name :
<button onClick={showMessage}>
Hello Sana
</button>
In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to prevent the default behavior.
File name :
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('Hello Sana');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}
Example
we have used only one component and adding an onChange event. This event will trigger the changeText function, which returns the company name.
File name :
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: ''
};
}
changeText(event) {
this.setState({
Name: event.target.value
});
}
render() {
return (
<div>
<h2>Event Example</h2>
<label htmlFor="name">Enter name: </label>
<input type="text" id="Name" onChange={this.changeText.bind(this)}/>
<h4>You entered: { this.state.Name }</h4>
</div>
);
}
}
export default App;
Example
File name :
import React from 'react';
import ReactDOM from 'react-dom';
function Tutorial() {
const shoot = () => {
alert("Great Concept!");
}
return (
<button onClick={shoot}>Click Here!</button>
);
}
ReactDOM.render(<Tutorial/>, document.getElementById('root'));
Passing Arguments
To pass an argument to an event handler, use an arrow function.
Send "Goal!" as a parameter to the shoot function, using arrow function:
File name :
import React from 'react';
import ReactDOM from 'react-dom';
function Mytutorial() {
const readconcept = (a) => {
alert(a);
}
return (
<button onClick={() => readconcept("Hello Sana!")}>Say Hello!</button>
);
}
ReactDOM.render(<Mytutorial />, document.getElementById('root'));
React Event Object
Event handlers have access to the React event that triggered the function. In our example the event is the "click" event.
File name :
import React from 'react';
import ReactDOM from 'react-dom';
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function.
In this case, the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));