patternjavascriptreactCritical
React js onClick can't pass value to method
Viewed 0 times
onclickmethodcanreactvaluepass
Problem
I want to read the onClick event value properties. But when I click on it, I see something like this on the console:
My code is working correctly. When I run I can see
My Code:
How can I pass a value to the
SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", targetMy code is working correctly. When I run I can see
{column} but can't get it in the onClick event.My Code:
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
{this.props.defaultColumns.map(function (column) {
return (
{column}
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( {externalColumnName});
})}
);
}
});How can I pass a value to the
onClick event in React js?Solution
Easy Way
Use an arrow function:
This will create a new function that calls
Better Way
Extract it into a sub-component.
The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
Sub-component
Main component
Old Easy Way (ES5)
Use
Use an arrow function:
return (
this.handleSort(column)}>{column}
);This will create a new function that calls
handleSort with the right params.Better Way
Extract it into a sub-component.
The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
Sub-component
class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
{this.props.column}
);
}
}Main component
{this.props.defaultColumns.map((column) => (
))}Old Easy Way (ES5)
Use
.bind to pass the parameter you want, this way you are binding the function with the Component context :return (
{column}
);Code Snippets
return (
<th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
<th onClick={this.handleClick}>
{this.props.column}
</th>
);
}
}{this.props.defaultColumns.map((column) => (
<TableHeader
value={column}
onHeaderClick={this.handleSort}
/>
))}return (
<th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);Context
Stack Overflow Q#29810914, score: 1672
Revisions (0)
No revisions yet.