4 years ago
Zarabia Riaz
3,037 Views
4
In this session, we will learn how to use events to react to JS with examples and codes.
Use of Event in React JS
React performs actions based on user events like HTML: click, change, mouse over, etc.
Creating Events
We will start by creating a form that has an input and a button. The use of the button is to call a function that will reverse that value easily.
How Creating Events will work
To enter text an empty input field is made for the user to enter the text in it.
By using the onChange method, an event is triggered when values are entered in the input field. This calls a function handlechange() that is used to set a new state for the input field.
With the help of the handleReverse( ) method another event is triggered, when the “Reverse Text” button is clicked to set a new state for reversed text.
Simple Example
We will only use one component in the following simple example. We are just adding an onClick method that will target the updateState function, once the button is clicked.
//App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated...'})
}
render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Once the button is clicked, we will get the following result.
Child Events
When we need to update the state of the parent component from its child, we can create an event handler (updateState ) in the parent component and pass it as a prop (updateStateProp ) to the child component where we can just call it.
//App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated from the child component...'})
}
render() {
return (
<div>
<Content myDataProp = {this.state.data}
updateStateProp = {this.updateState}></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<button onClick = {this.props.updateStateProp}>CLICK</button>
<h3>{this.props.myDataProp}</h3>
</div>
);
}
}
export default App;
//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Once the button is clicked, we will get the following result
4 years ago
Zarabia Riaz
3,037 Views
4