Reputation: 1136
I have a React app in which upon clicking on a column heading, the table sorts the data (via a merge sort).
I want to pass the data (i.e., an array of objects) and the event object. I want to use the event object to get the value of the column clicked, so to then use it to sort the data.
However, I keep getting an error message that the event object is undefined.
Below is the relevant portion of the code:
sortColumn (siteArr, evt) {
if (siteArr.length < 2) {
return siteArr;
} else {
const column = evt.target.value; // evt returns undefined
const midPoint = Math.round(siteArr.length / 2);
const subLeft = this.sortColumn(siteArr.slice(0, midPoint));
const subRight = this.sortColumn(siteArr.slice(midPoint));
return this.merge(column, subLeft, subRight);
}
}
merge (column, left, right) {
const out = [];
while (left.length && right.length) {
out.push(left[0][column] <= right[0][column] ? left.shift() : right.shift());
}
while (left.length) {
out.push(left.shift());
}
while (right.length) {
out.push(right.shift());
}
this.setState({sites: out});
return out;
}
render () {
const siteArr = this.state.sites;
const sites = this.state.sites.map((site) => {
return (
<Site site={site} key={site.id} />
);
});
const site_number = sites.length;
return (
<div>
<table>
<thead>
<tr>
<th><a onClick={(evt) => this.sortColumn(siteArr, evt)}>Name</a></th>
<th><a onClick={(evt) => this.sortColumn(siteArr, evt)}>City</a></th>
<th><a onClick={(evt) => this.sortColumn(siteArr, evt)}>State</a></th>
</tr>
</thead>
<tbody>
{sites}
</tbody>
</table>
</div>
);
}
a) How do I pass the event object to the sortColumn function?
b) How do I access the column value via the event object?
Thanks for any help you can provide!
Upvotes: 2
Views: 1214
Reputation: 20614
For your situation because you already know what the text value is, just pass that to your function:
() => this.sortColumn(siteArr, 'Name')
However if you want to get the innerText value of the target, that's what you use:
event => this.sortColumn(siteArr, event.target.innerText)
Upvotes: 2