For the Javascript, when an event occurs, a function will be called to execute. But for the React, when an event occurs, a method of Component is called. This example component renders a div that responds to click events.
var BannerAd = React.createClass({
onBannerClick: function(evt) {
// codez to make the moneys
},
render: function() {
// Render the div with an onClick prop (value is a function)
return <div onClick={this.onBannerClick}>Click Me!</div>;
}
});
That’s it. You add onXXX to the nodes you want. Notice how the value of the prop is a function.
Example
This is a simple example where we will only use one component. We are just adding onClick event that will trigger 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’));
Arrow Function
With the Javascript ES6 syntax, you can create an arrow function, which is very short and easy-to-understand:
// Normal function with parameters
var myfunc = function(param1, param2) {
// Statements
};
// Arrow function with parameters.
var arrfunc = (param1, param2) => {
// Statements
};