Reputation: 618
I have below child component in react which I am rendering on button click event in parent component. Till here I have no problem. Table is getting rendered on page. I have written row click event findDetails() on table. But problem is that rowClick event in not working on row click. Instead of that it get executed when component is rendering on page. I want to execute on rowClick. Below is my code for table component. Also I need to implement pagination as well in same table which I am not sure how to do it.
class Table extends Component {
constructor(props) {
super(props);
this.state = {
};
}
getHeaader = () => {
var tableHeadings = [
"Customer ID",
"Customer Name",
"Address",
"Contact",
];
return tableHeadings.map((key) => {
return <th key={key}> {key.toUpperCase()}</th>;
});
};
getRowsData = (e) => {
return this.props.Data.map((value, index) => {
const {
"Customer_ID",
"Customer_Name",
"Address",
"Contact",
} = value;
return (
<tr
key={CUSTOMER_ID}
onClick={this.findDetails(value)}
>
<td> {CUSTOMER_ID} </td>
<td> {CUSTOMER_NAME} </td>
<td> {Address} </td>
<td> {Contact} </td>
<td>
<button className="btn btn-info">Find Details</button>
</td>
</tr>
);
});
};
findDetails = (value) => {
console.log("in show button", value.count);
if (value["count"] === 0) {
alert("No details for given customer");
}
};
render() {
return (
<div>
<table
id="display-table"
className="table table-bordered table table-hover table table-responsive pagination"
style={{ tableLayout: "fixed" }}
>
<tbody>
<tr>{this.getHeaader()}</tr>
{this.getRowsData()}
</tbody>
</table>
</div>
);
}
}
export default Table;
`
Upvotes: 0
Views: 740
Reputation: 1001
You invoke your onClick in the wrong way. When passing parameters, you have to wrap your function in an anonymous one:
<tr
key={CUSTOMER_ID}
onClick={() => this.findDetails(value)}
>
I'll explain. When passing onClick
, React is waiting for a function name (actually a reference), that then it calls, by adding parentheses. If you add them by yourself as you did (onClick={this.findDetails()
} ) you invoke the function right away and you pass the RESULT of the function to the onClick
listener.
Upvotes: 1