I'm trying to achieve selecting just only one row at a time in my React Material App. My problem now is that it is highlighting many rows. I only need to highlight/select one row at a time.
Pls check this codesandbox link
CODE
const [selected, setSelected] = React.useState([]);
const selectFood = (event, food) => {
const selectedIndex = selected.indexOf(food.name);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, food.name);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1)
);
}
setSelected(newSelected);
};
const isSelected = row => selected.indexOf(row.name) !== -1;
If you want to just select a single row - then this would work definitely ( no need of complex code which you have written )
const selectFood = (event, food) => {
let newSelected = [food.name];
setSelected(newSelected);
};
Working link - https://codesandbox.io/s/highlightselect-rows-react-material-8ejbc?file=/demo.js:1016-1123
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.