Thian Kian Phin Thian Kian Phin - 2 months ago 9
React JSX Question

react on click doesn't work with arrow function

Something is wrong with my code below? I try to use the arrow function, but nothing happens.

class App extends React.Component {
promt() => {
alert('trigger prompt!');
},
render(){
return(
<h1 onClick="this.promt()">Hello world</h1>
)
}
}

ReactDOM.render(<App />,document.getElementById('app-container'));


https://jsbin.com/nisetupaqa/edit?html,js,console,output

Answer

You've got some incorrect syntax. promt() => { ... } is invalid for ES6 classes. To achieve arrow functions, you must assign it, as a class property, like so:

promt = () => {
    alert("trigger prompt");
}

Note that class properties are an experiment feature, in stage-2, which has not been fully implemented. Per the documentation:

Stage-X (Experimental Presets)

Any transforms in stage-x presets are changes to the language that haven’t been approved to be part of a release of Javascript (such as ES6/ES2015).

“Changes to the language are developed by way of a process which provides guidelines for evolving an addition from an idea to a fully specified feature”

Subject to change These proposals are subject to change so use with extreme caution, especially for anything pre stage-3.

In the meantime, just use regular ES6 class functions:

promt() {
    alert("trigger prompt");
}

Also, no commas between functions. Also, use { } to reference functions as handlers, do not use strings. That means that this:

<h1 onClick="this.promt()">Hello world</h1>

is incorrect. Wrap the reference in curly braces, and remove the parentheses, as you need a function reference, not invocation:

<h1 onClick={this.promt}>Hello world</h1> 

Here's a fiddle that is working.