Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  186] [ 7]  / answers: 1 / hits: 8961  / 3 Years ago, tue, june 15, 2021, 12:00:00

hi i'm really new in react, so i have a table which contains a bunch of data, i would like to assign the value of selected row to my setState but the output doesnt seems like what i expected to be, i made a simpler version of the code so here it is.


App.js :


import React from "react";
import DataTable from "react-data-table-component";

const app = () => {
const [selectedData, setSelectedData] = React.useState();

const data = [
{ name: "Jade", age: "25" },
{ name: "Brian", age: "15" }
];

const columns = [
{
name: "Name",
selector: "name"
},
{
name: "Age",
selector: "age"
}
];

const handleChange = (state) => {
setSelectedData(state.selectedRows);
console.log(selectedData);
};

return (
<div>
<DataTable
data={data}
columns={columns}
selectableRows
onSelectedRowsChange={handleChange}
/>
</div>
);
};

export default app;

Codesandbox


More From » reactjs

 Answers
2

solved this issue by moving the data variable to global scope, this happen because the data variables keeps re-rendering inside the component


import DataTable from "react-data-table-component";

const data = [
{ name: "Jade", age: "25" },
{ name: "Brian", age: "15" }
];

const app = () => {
const [selectedData, setSelectedData] = React.useState();

const columns = [
{
name: "Name",
selector: "name"
},
{
name: "Age",
selector: "age"
}
];

const handleChange = (state) => {
setSelectedData(state.selectedRows);
console.log(selectedData);
};

return (
<div>
<DataTable
data={data}
columns={columns}
selectableRows
onSelectedRowsChange={handleChange}
/>
</div>
);
};

export default app;```

[#1239] Monday, June 7, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;