In the last lesson, we set up state and I told you that it would be special that we dont really see that yet. All we have done now is manage our data thereand then access in our JSX code in the App.js file. Now let us see Events in React.
Events In React
let us now handle click on this button we can di that by adding onClick
...
<button onClick={}>Switch Name</button>
...
In normal javascript and normal HTML it would be
onclick
with lowercase c. Now in JSX and that is really important it’s onClick
with capital C.Now typically we want to execute a function of our class or so called method and this is a convention to give this name like the following switchNameHandler
the first part switchName
is totally up to you but typically use handler
here to indicate that this is a method which we are not actively calling but we assigning as an event handler. It’s not required to follow this pattern though so you can name this what ever you want ofcourse as it is a good practice.
So switchNameHandler
now should b a function, to create a function we will use the ES6 arrow function
...
switchNameHandler = () => {
alert('it clicked');
}
...
And there I now want to edit my state before we do that let’s see if we can call that successfully by adding alert on click event,
Now will add that method to click listener and bewween curly braces we can run that function (switchNameHandler
).
...
<button onClick={this.switchNameHandler}>Switch Name</button>
...
Dont use function with parentheses e.g. [
this.switchNameHandler()
]. it will execuate immediately once React renders this to the dom because we execuate switchNameHandler()
function with the parenthesis.We only want to pass a refrence and we do this by using this
and then referring to that property which holds a function.
if you don’t use the ES6 arrow function syntax where we assign a function to a property you could say, we will run into errors if you try to use
this
as we will soon do in that function. Because this
will not refer to the class
at runtime.By using this ES6 syntax we will find a way around, this problem which will become important later.
now just save that file and open up in browser and click the button to view the alert on click of the switch name button.
import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
persons: [{ name: 'Lucy', age: 23 }, { name: 'Max', age: 12 }, { name: 'Mike', age: 34 }],
};
switchNameHandler = () => {
alert('called');
};
render() {
return (
<div className="App">
<h1> Heading</h1>
<button onClick={this.switchNameHandler}>Switch Name</button>
<Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
{/* goes on */}
</div>
);
}
}
export default App;
In the next lesson we will see how we can change the state.