Putting this here for my own reference so I don’t forget it. I had the following code in a React component and couldn’t for the life of me figure out why the onclick never fired. I would also get the error this.editClause is not a function
editClause = (clause) => {
console.log("edit clause");
}
static renderSoaTable(clauses) {
return (
<table className="table table-striped" aria-labelledby="tableLabel">
<thead>
<tr>
<th></th>
<th>Clause</th>
<th>Name</th>
<th>Description</th>
<th>Applicable</th>
<th>Justification</th>
</tr>
</thead>
<tbody>
{clauses.map(clause =>
<tr key={clause.id} onClick={() => this.editClause(clause) }>
<td><input type="checkbox" /></td>
<td>{clause.clauseId}</td>
<td >{clause.name}</td>
<td>{clause.description}</td>
<td>{clause.applicable}</td>
<td>{clause.justification}</td>
</tr>
)}
</tbody>
</table>
);
}
It was only after several attempts that I realised what I should have realised from the beginning when you code in C# you can only call static functions from other static functions. That is very much also the case with JavaScript, so to resolve the issue I could do this. Note how I have made the editClause static?
static editClause = (clause) => {
console.log("edit clause");
}
static renderSoaTable(clauses) {
return (
<table className="table table-striped" aria-labelledby="tableLabel">
<thead>
<tr>
<th></th>
<th>Clause</th>
<th>Name</th>
<th>Description</th>
<th>Applicable</th>
<th>Justification</th>
</tr>
</thead>
<tbody>
{clauses.map(clause =>
<tr key={clause.id} onClick={() => this.editClause(clause) }>
<td><input type="checkbox" /></td>
<td>{clause.clauseId}</td>
<td >{clause.name}</td>
<td>{clause.description}</td>
<td>{clause.applicable}</td>
<td>{clause.justification}</td>
</tr>
)}
</tbody>
</table>
);
}
However, if I don’t want to make editClause static, I could construct my code like this instead.
static renderSoaTable(clauses, editClause) {
return (
<table className="table table-striped" aria-labelledby="tableLabel">
<thead>
<tr>
<th></th>
<th>Clause</th>
<th>Name</th>
<th>Description</th>
<th>Applicable</th>
<th>Justification</th>
</tr>
</thead>
<tbody>
{clauses.map(clause =>
<tr key={clause.id} onClick={() => editClause(clause) }>
<td><input type="checkbox" /></td>
<td>{clause.clauseId}</td>
<td >{clause.name}</td>
<td>{clause.description}</td>
<td>{clause.applicable}</td>
<td>{clause.justification}</td>
</tr>
)}
</tbody>
</table>
);
}
Here I am passing in editClause into the renderSoaTable function when I call it.