I have a component that is receiving a list of records as a prop. I'm trying to add a function to an onClick event, but the code set to be executed on the click event is firing as soon as the component loads. In this case I'm referring to the processM function. I'm new to ReactJS and I would appreciate any help.
var TempJobTaskActions = React.createClass({
processM: function(url){
console.log('in processMove: ', url);
$.ajax({
type: 'GET',
url: url,
success: function(data){
}
});
},
render: function(){
var action = null;
var downUrl = '../MoveDown?id='+this.props.tid;
var upUrl = '../MoveUp?id='+this.props.tid;
if(this.props.position == "solo"){
action = (<span></span>);
}
if(this.props.position == "first"){
action = (<span><a className='cdc-link cdc-icon glyphicon glyphicon-arrow-down'
href='#' onClick={this.processM(downUrl)} title='Move Down'></a></span>);
}
if(this.props.position == "last"){
action = (<span><a className='cdc-link cdc-icon glyphicon glyphicon-arrow-up'
href='#' onClick={this.processM(upUrl)} title='Move Up'></a></span>);
}
if(this.props.position == "middle"){
action = (
<div>
<span><a className='cdc-link cdc-icon glyphicon glyphicon-arrow-up'
href='#' onClick={this.processM(upUrl)} title='Move Up'></a></span>
<span><a className='cdc-link cdc-icon glyphicon glyphicon-arrow-down'
href='#' onClick={this.processM(downUrl)} title='Move Down'></a></span>
</div>
);
}
return (
<div>{action}</div>
);
}
});
Example: Call a Function After Clicking a Buttonimport React from 'react'; function App() { function sayHello() { alert('Hello!' ); } return ( <button onClick={sayHello}> Click me! </button> ); } export default App; The simple App component above has one function called sayHello(), and a single button.
In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...
onClick Event Handler in ReactJsWhenever the user clicks a button or any element within our application, the onClick event calls a function, and the called function triggers an action. The event handlers in React always appear within the curly braces.
To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.
this.processM(upUrl)
will call the function. To send variables you should bind like this instead
this.processM.bind(this, upUrl)
Here is a good example with bind
Try rewriting the call as an ES6 arrow function:
onClick={() => {
this.processM(downUrl);
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With