I need to add new column to react-table when button click, even after re-rendering table with flag Iam unable to add new column, can you please suggest on where am I gone wrong. Here is the executable sandbox code.
https://codesandbox.io/s/tannerlinsley-react-table-row-selection-forked-3gcwm?file=/src/App.js
Advertisement
Answer
You need to keep a state for the columns and change it accordingly using the setter method. Try like below:
JavaScript
x
38
38
1
const intialColumns = [
2
{
3
Header: "Units",
4
accessor: "units",
5
width: 400
6
},
7
{
8
Header: "Units1",
9
accessor: "units1",
10
width: 400
11
}
12
];
13
14
function App() {
15
const [columns, setColumns] = useState(intialColumns);
16
17
const addColumn = () => {
18
setColumns((prevCols) => [
19
prevCols,
20
{
21
Header: "Units3",
22
accessor: "units3",
23
width: 400
24
}
25
]);
26
};
27
const data = React.useMemo(() => makeData(100), []);
28
29
return (
30
<Styles>
31
<button style={{ margin: "5px" }} onClick={addColumn}>
32
click here to add column{" "}
33
</button>
34
<Table columns={columns} data={data} />
35
</Styles>
36
);
37
}
38
Codesandbox: