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.
let us now handle click on this button we can di that by adding onClick
onClick
... <button onClick={}>Switch Name</button> ...
onclick
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
switchName
handler
... 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> ...
this.switchNameHandler()
switchNameHandler()
We only want to pass a refrence and we do this by using this and then referring to that property which holds a function.
this
class
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.