Tutorials

ReactJS Tutorial - Basics


ReactJS - Event Handling


Event handling in reactJS is similar to that of HTML but there are some syntactic differences because react uses JSX and not HTML.

React uses camelCase for event names

For example in HTML

<button onclick=”formatName();”>

Format Name

</button>

In React

<button onClick={formatName}>

Format Name

</button>

React uses function as event handler and not string

Remember anything written between curly braces is javascript and formatName is a method

To use formatName as event handler you have to use

this.formatName=this.formatName.bind(this); 

This is not specific to React but it comes from es6 specification.

 

return false cannot prevent default behavior in React

Consider following piece of code which prevents the default behavior on anchor tag in HTML but will not work in react.

<a href="#" onclick="console.log(‘clicked!!'); return false">
  Click Me
</a>

To prevent the default behavior in React you can create event handler and prevent the default behavior by calling event.preventDefault() for example below will work fine.

function handleClick(e) {
    e.preventDefault();
    console.log('clicked!!!.');
  }

You can pass arguments to event handler

have a look on below code

class App extends React.Component{
constructor(props)
{
 super(props);
}
handleClick(data,event){
 console.log(data);
}
render(){
return (
<div>
<button onClick={(e)=>{this.handleClick("id1",e);}}>edit row 1</button>
<button onClick={(e)=>{this.handleClick("id2",e);}}>edit row 2</button>
</div>
);
}
}
ReactDOM.render(<App/>,mountNode)

Since I have called handleClick from arrow function so we do not need to bind it. When you click on buttons then you will be able to pass id1 and id2 to event handler.

You can also write event handler as below

<div>
<button onClick={(e)=>{this.handleClick.bind("id1",e);}}>edit row 1</button>
<button onClick={(e)=>{this.handleClick.bind("id2",e);}}>edit row 2</button>
</div>

try it out on the js repl https://jscomplete.com/repl and see the results



Please Share this page
Views : 76
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!