Adam White Adam White - 1 year ago 127
React JSX Question

Passing event object in onClick function in React

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 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) {
while (right.length) {
this.setState({sites: out});
return out;
render () {
const siteArr = this.state.sites;
const sites = => {
return (
<Site site={site} key={} />
const site_number = sites.length;
return (
<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>

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!

Answer Source

For your situation because you already know what the text value is, just pass that to your function:

() => this.sortColumn(site‌​Arr, 'Name')

However if you want to get the innerText value of the target, that's what you use:

event => this.sortColumn(siteArr,
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download