I have a table using normal HTML in reactjs:
const [user, setUser] = useState(null);
useEffect(() => {
axios
.get("http://localhost:8080/api/users")
.then((response) => {
setUser(response.data);
});
}, [url]);
const [rowIndex, setRowIndex] = useState("");
if (user) {
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Department</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{user.map((item) => (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.department}</td>
<td><button>Click</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
}
If in Javascript, I can simply set <tr onclick="getIndex(this)">
and calling function getIndex(x) {console.log(x.rowIndex)}
to get the row number.
But it's not working in ReactJS. How can I get the rowIndex in ReactJS?
CodePudding user response:
Use index inside your map
method and then use this variable inside your button's onClick
method
const [user, setUser] = useState(null);
useEffect(() => {
axios
.get("http://localhost:8080/api/users")
.then((response) => {
setUser(response.data);
});
}, [url]);
const [rowIndex, setRowIndex] = useState("");
if (user) {
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Department</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{user.map((item, index) => (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.department}</td>
<td><button onclick={() => setRowIndex(index)}>Click</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
}
CodePudding user response:
Try this:
<tbody>
{user.map((item, rowIndex) => (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.department}</td>
</tr>
)}
</tbody>