Reputation: 747
I have a react table that looks like this. I want to be able to click each individual cell and get the value. I know you can get the entire row, but I only want each individual cell when it's clicked so I can save it in state like this
{
"Team": GB,
"MoneyLine": -120
}
{
"Team": GB,
"Spread": 1
}
{
"Team": GB,
"MoneyLine": -120,
"Spread": -1,
"Total": 48
}
I tried this link How to get cell value on React-Table?
but it doesn't provide much explanation.
I need to get the team name whenever any cell in the row is clicked and then the specific value that is clicked.
Here is the code
import React, { useState } from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import data from '../Data/data.json'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()} >{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, _) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()} >{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
)
}
export default function PicksTable(){
const [team, setTeam] = useState('');
const [moneyLine, setMoneyLine] = useState('');
const [spread, setSpread] = useState('');
const [total, setTotal] = useState('');
const columns = React.useMemo(
() => [
{
Header: 'Teams',
columns: [
{
Header: 'Team',
accessor: 'team',
},
],
},
{
Header: 'Betting Info',
columns: [
{
Header: 'Money Line',
accessor: 'moneyLine',
},
{
Header: 'Spread',
accessor: 'spread',
},
{
Header: 'Total',
accessor: 'total',
},
],
},
],
[]
)
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
Upvotes: 2
Views: 7269
Reputation: 1535
You need to add onClick to <td>
(values are in row and cell):
<td
onClick={() => console.info(row.values.team, cell.value)}
{...cell.getCellProps()}
>
Here is a full working CodeSandbox: https://codesandbox.io/s/fervent-shape-jr8tm?file=/src/App.js:1325-1489
Upvotes: 3