Reputation: 63
In the below shown Users.jsx file I am populating a table with the data stored in the userList array. I have implemented an onClick listener in a table data cell element, I want the Trigger function to be called with the clicked row's info object. Or I want to be able to access the clicked row's data in the Trigger function.
import React from 'react';
import '../../node_modules/bootstrap/dist/css/bootstrap.min.css'
import Navbar from "../components/NavBar";
import { Table } from 'react-bootstrap';
function Users() {
let userList = [
{'name': 'Jack',
'age': 21,
'role': 'Customer',
},
{'name': 'Tom',
'age': 22,
'role': 'Product Manager',
}]
const Trigger = () => {
// Here
}
const UserData = userList.map(
(info)=>{
return(
<tr>
<td>{info.name}</td>
<td>{info.age}</td>
<td>{info.role}</td>
<td onClick={Trigger}> Visit Profile </td>
</tr>
)
}
)
return(
<div>
<Navbar/>
<div>
<div className="row">
<div className="col-md-8 offset-md-2">
<Table striped bordered hover responsive="md">
<thead>
<tr>
<th>NAME</th>
<th>AGE</th>
<th>ROLE</th>
<th>PROFILE</th>
</tr>
</thead>
<tbody>
{UserData}
</tbody>
</Table>
</div>
</div>
</div>
</div>
)
}
export default Users;
Any help with a solution or recommendation to documentation for (event handlers needed in this context) will be much appreciated.
Upvotes: 1
Views: 3820
Reputation: 46
An arrow function call would do the job:
let userList = [
{'key': 1,
'name': 'Jack',
'age': 21,
'role': 'Customer',
},
{'key': 2,
'name': 'Tom',
'age': 22,
'role': 'Product Manager',
}]
const Trigger = (info) => {
// Here
console.log(`Name is: ${info.name}, Age: ${info.age}, Role: ${info.role}`)
}
const UserData = userList.map(
(info)=>{
return(
<tr key={info.key}>
<td>{info.name}</td>
<td>{info.age}</td>
<td>{info.role}</td>
<td onClick={() => Trigger(info)}> Visit Profile </td>
</tr>
)
}
)
P.S I've added keys to the list to avoid warnings..
Upvotes: 2
Reputation: 376
function Users() {
let userList = [
{'name': 'Jack',
'age': 21,
'role': 'Customer',
},
{'name': 'Tom',
'age': 22,
'role': 'Product Manager',
}]
const Trigger = (info) => {
// info it's user obj
}
const UserData = userList.map(
(info)=>{
return(
<tr>
<td>{info.name}</td>
<td>{info.age}</td>
<td>{info.role}</td>
<td onClick={()=>{Trigger(info)}}> Visit Profile </td>
</tr>
)
}
)
return(
<div>
<Navbar/>
<div>
<div className="row">
<div className="col-md-8 offset-md-2">
<Table striped bordered hover responsive="md">
<thead>
<tr>
<th>NAME</th>
<th>AGE</th>
<th>ROLE</th>
<th>PROFILE</th>
</tr>
</thead>
<tbody>
{UserData}
</tbody>
</Table>
</div>
</div>
</div>
</div>
)
}
export default Users;
Upvotes: 1