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!
event.target.valueto equal? The inner text value like Name or City ?event.target.valuegives you, but it doesn't look like you would need it here because you already have the text value right next to it. why not just() => this.sortColumn(siteArr, 'Name')?