Managing with objects inside of array React state - arrays

I am trying to manage objects inside of an array. So I have array item which has some objects.
state = {
item: [
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
],
loader: true
};
I added a method which changes the image on click, but it changes the image in all objects
likedBtn = () => {
this.setState((prevState) => ({
item: prevState.item.map(
obj => (obj.heart === heart ? Object.assign(obj, {heart: heartRed}): obj)
)
}));
console.log('liked');
}
How can I assign that method to prevent acting on all the objects inside of an array?
<ProductsItems liked={this.likedBtn} addToCart={this.clickHandler} cls={item.cls} img={item.img} productName={item.productName} price={item.price} heart={item.heart} />
Sorry for such a dumb explanation but I hope you'll understand it. The heart is blue and it is red when clicked. That is all that I need but when I click only the one heart, all others change as well

This would do it
state = {
item: [
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
{
cls: 'powder',
img: ariel_12,
productName: 'Стиральный порошок Ariel 1,5 КГ',
price: 200,
heart: heart,
qty: 1
},
],
loader: true
};
render(){
<div>
{this.state.item.map( (obj,index) => {
<div
key={index}
onClick={() => this.handleClick(index)}
liked={this.likedBtn}
cls={obj.cls}
img={obj.img}
productName={obj.productName}
price={obj.price}
heart={obj.heart}
>
</div>
})}
</div>
}
handleClick = index => {
this.setState( prevState => (prevState.item[index].heart = heartRed, prevState)
}

Related

line 14 Expected an assignment or function call and instead saw an expression error

I'm am trying to map over seeded data, and I'm getting this error. Does anyone know why? Right now I am only trying to get the key of name to display, but I'm getting an expected an assignment or functionn error.
import { Link } from "react-router-dom";
import {getData} from "../Data"
export default function Home() {
let data = getData();
return (
<div>
{data.map((data) => {
{data.name}
})}
</div>
)
}
This is my seed data that I am trying to pull from.
I have imported it in my home.jsx file and called the function before my return statement.
let data = [
{
name: 'forgive-me-pleases',
image: 'https://i.imgur.com/0UCzcZM.jpg',
price: 50,
tags: ['pink', 'roses', 'bouquet', 'apologies'],
},
{
name: 'pink perfection',
image: 'https://i.imgur.com/XoEClf7.png',
price: 15,
tags: ['pink', 'gerbera daisy', 'singular', 'decor'],
},
{
name: 'hopeful sunshine',
image: 'https://i.imgur.com/LRrcBtN.png',
price: 30,
tags: ['yellow', 'sunflower', 'multiple', 'garden'],
},
{
name: 'motivational mug',
image: 'https://i.imgur.com/NOJ2ikN.png',
price: 25,
tags: ['yellow', 'gerbera daisy', 'singular (with mug)'],
},
{
name: 'breathtaking bouquet',
image: 'https://i.imgur.com/TuuKiHt.png',
price: 40,
tags: ['white', "baby's breath", 'bouquet', 'decor'],
},
{
name: 'loves-me-loves-me-knots',
image: 'https://i.imgur.com/SaTbTEx.png',
price: 20,
tags: ['mixed', 'gerbera daisy', 'mini bouguet', 'for fun'],
},
{
name: 'hiya, spring',
image: 'https://i.imgur.com/dJvHolr.jpg',
price: 35,
tags: ['mixed', 'hyacinths', 'bouquet', 'garden'],
},
{
name: 'can of compassion',
image: 'https://i.imgur.com/PN3jmrf.png',
price: 55,
tags: ['mixed', 'decor', 'bouquet (with can)', 'love'],
},
{
name: 'basket of beauty',
image: 'https://i.imgur.com/Z86X3qq.png',
price: 50,
tags: ['mixed', 'bouquet (with basket)', 'love', 'decor'],
},
];
export function getData() {
return data
}
Please change your code like below
let data = getData();
return (
<div>
{data.map((data) => {
<div>{data.name}</div>
})}
</div>
)

How to change color of specific items returen from map list

I want to change border or outline color when I click for one item not all list items
but when I click on any items all list changed
I'm trying to change one item color not all...so when I change state it changed for all not for item I clicked
const [color,setColor]=useState('');
type Values = {
id: number;
title: string;
image: string;
color:string;
};
const myList2:Array<Values> =[
{
id: 1,
title: 'Suitcase',
image: suitcase,
color:'blue',
},
{
id: 2,
title: 'Briefcase',
image: briefcase,
color:'aqua',
},{
id: 3,
title: 'Handbage',
image: handbage,
color:'red',
},
{
id: 4,
title: 'Multy',
image: multy,
color:'green',
},
{
id: 5,
title: 'Backpack',
image: backpack,
color:'gray',
},
{
id: 6,
title: 'Family',
image: family,
color:'orange',
},
]
const listImage=myList2.map((item,i) => {
return <span key={i}>
<img key={item.id} style={{borderColor:color}} onClick={()=>setColor(item.color)} src={item.image} alt={item.title} />
</span>
})
Currently you are setting only color name in the state variable but not specify that for which index this color will apply
So simply store only index to the state variable on which user click by adding onClick={()=>setActive(i)} in the image tag
and finally check the condition in style by adding style={{borderColor: active == i ? item.color : 'transparent', borderWidth: 3}} in the image tag
const [active,setActive]=useState(-1);
type Values = {
id: number;
title: string;
image: string;
color:string;
};
const myList2:Array<Values> =[
{
id: 1,
title: 'Suitcase',
image: suitcase,
color:'blue',
},
{
id: 2,
title: 'Briefcase',
image: briefcase,
color:'aqua',
},{
id: 3,
title: 'Handbage',
image: handbage,
color:'red',
},
{
id: 4,
title: 'Multy',
image: multy,
color:'green',
},
{
id: 5,
title: 'Backpack',
image: backpack,
color:'gray',
},
{
id: 6,
title: 'Family',
image: family,
color:'orange',
},
]
const listImage=myList2.map((item,i) => {
return <span key={i}>
<img key={item.id} style={{borderColor: active == i ? item.color : 'transparent', borderWidth: 3}} onClick={()=>setActive(i)} src={item.image} alt={item.title} />
</span>
})
You can use the id for that. So instead of only the color name, keep two pieces of information as an object inside the state variable => id, color.
Like this:
const [selectedList, setSelectedList] = useState({});
const listImage=myList2.map((item,i) => {
return <span key={i}>
<img key={item.id}
style={item.id === selectedList.id ? { borderColor: selectedList.color } : {}}
onClick={() => setSelectedList({id: item.id, color: item.color})}
src={item.image} alt={item.title} />
</span>
})

How to show length of filtered items using react redux. Im getting data using list. Using list how can i get the length of filtered items length

This is shop page.jsx file here i want to show the list of filtered items at the top of the page. Here im using data list for getting all the details. Here i want to show length of filtered products at showing 9 0f 9 products.
import React, { useEffect, useState } from 'react';
import EmptyView from '../components/common/EmptyView';
import FilterPanel from '../components/Home/FilterPanel';
import List from './Home/List';
// import SearchBar from '../../components/Home/SearchBar';
import { dataList } from '../constants';
// import './styles.css';
import '../App.css';
import ButtonAppBar from "./Header";
const Shop = () => {
// const [selectedCategory, setSelectedCategory] = useState(null);
// const [selectedRating, setSelectedRating] = useState(null);
const [selectedPrice, setSelectedPrice] = useState([0, 150]);
const [cuisines, setCuisines] = useState([
{ id: 1, checked: false, label: 'Furniture' },
{ id: 2, checked: false, label: 'Decoration' },
{ id: 3, checked: false, label: 'Bedding' },
{ id: 4, checked: false, label: 'Lighting' },
{ id: 5, checked: false, label: 'Bath&Shower' },
{ id: 6, checked: false, label: 'Curtains' },
{ id: 7, checked: false, label: 'Toys' },
]);
const [brand, setBrand] = useState([
{ id: 1, checked: false, label: 'Poliform' },
{ id: 2, checked: false, label: 'Rochie Bobois' },
{ id: 3, checked: false, label: 'Edra' },
{ id: 4, checked: false, label: 'Kartell' },
]);
const [availability, setAvailability] = useState([
{ id: 1, checked: false, label: 'Onstock' },
{ id: 2, checked: false, label: 'Outofstock' },
]);
const [list, setList] = useState(dataList);
const [resultsFound, setResultsFound] = useState(true);
// const [searchInput, setSearchInput] = useState('');
// const handleSelectCategory = (event, value) =>
// !value ? null : setSelectedCategory(value);
// const handleSelectRating = (event, value) =>
// !value ? null : setSelectedRating(value);
const handleChangeChecked = (id) => {
const cusinesStateList = cuisines;
const changeCheckedCuisines = cusinesStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setCuisines(changeCheckedCuisines);
};
const handleChangeCheckeds = (id) => {
const brandStateList = brand;
const changeCheckedsBrand = brandStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setBrand(changeCheckedsBrand);
};
const handleChangeCheckedss = (id) => {
const availabilityStateList = availability;
const changeCheckedssAvailability = availabilityStateList.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setAvailability(changeCheckedssAvailability);
};
const handleChangePrice = (event, value) => {
setSelectedPrice(value);
};
const applyFilters = () => {
let updatedList = dataList;
// // Rating Filter
// if (selectedRating) {
// updatedList = updatedList.filter(
// (item) => parseInt(item.rating) === parseInt(selectedRating)
// );
// }
// // Category Filter
// if (selectedCategory) {
// updatedList = updatedList.filter(
// (item) => item.category === selectedCategory
// );
// }
// Cuisine Filter
const cuisinesChecked = cuisines
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (cuisinesChecked.length) {
updatedList = updatedList.filter((item) =>
cuisinesChecked.includes(item.cuisine)
);
}
// brand filter
const brandChecked = brand
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (brandChecked.length) {
updatedList = updatedList.filter((item) =>
brandChecked.includes(item.brand)
);
}
// availabilty filter
const availabilityChecked = availability
.filter((item) => item.checked)
.map((item) => item.label.toLowerCase());
if (availabilityChecked.length) {
updatedList = updatedList.filter((item) =>
availabilityChecked.includes(item.availability)
);
}
// // Search Filter
// if (searchInput) {
// updatedList = updatedList.filter(
// (item) =>
// item.title.toLowerCase().search(searchInput.toLowerCase().trim()) !==
// -1
// );
// }
// // Price Filter
const minPrice = selectedPrice[0];
const maxPrice = selectedPrice[1];
updatedList = updatedList.filter(
(item) => item.price >= minPrice && item.price <= maxPrice
);
setList(updatedList);
!updatedList.length ? setResultsFound(false) : setResultsFound(true);
};
useEffect(() => {
applyFilters();
}, [cuisines, brand, availability, selectedPrice]);
return (
<div>
<ButtonAppBar />
<div className='home'>
{/* Search Bar */}
{/* <SearchBar
value={searchInput}
changeInput={(e) => setSearchInput(e.target.value)}
/> */}
<br /><br /><br /> <div className='home_panelList-wrap'>
{/* Filter Panel */}
<div className='home_panel-wrap'>
<FilterPanel
// selectedCategory={selectedCategory}
// selectCategory={handleSelectCategory}
// selectedRating={selectedRating}
selectedPrice={selectedPrice}
// selectRating={handleSelectRating}
cuisines={cuisines}
changeChecked={handleChangeChecked}
brand={brand}
changeCheckeds={handleChangeCheckeds}
availability={availability}
changeCheckedss={handleChangeCheckedss}
changePrice={handleChangePrice}
/>
</div>
{/* List & Empty View */}
<div className='home_list-wrap'>
<h6>Showing
<span style={{ color: "#bd744c" }}><b>{dataList.length}</b></span> of
<span style={{ color: "#bd744c" }}><b>9</b></span>
Products</h6>
{resultsFound ? <List list={list} /> : <EmptyView />}
</div>
</div>
</div>
</div>
);
};
export default Shop;
This is constant.js file from here we are getting all our details in shop.jsx file.
export const dataList = [
{
id: 1,
title: 'AwesomeLamp',
cuisine: 'lighting',
price: 40,
image: '/images/AwesomeLamp.png',
brand: 'poliform',
availability: 'onstock',
name: 'AwesomeLamp',
tagName: 'AwesomeLamp'
},
{
id: 2,
title: 'CozySofa',
cuisine: 'furniture',
price: 150,
image: '/images/CozySofa.png',
brand: 'edra',
availability: 'outofstock',
name: 'CozySofa',
tagName: 'CozySofa'
},
{
id: 3,
title: 'AwesomeCandle',
cuisine: 'lighting',
price: 15,
image: '/images/AwesomeCandle.png',
brand: 'kartell',
availability: 'onstock',
name: 'AwesomeCandle',
tagName: 'AwesomeCandle',
},
{
id: 4,
title: 'FancyChair',
cuisine: 'furniture',
price: 70,
image: '/images/FancyChair.png',
brand: 'poliform',
availability: 'outofstock',
name: 'FancyChair',
tagName: 'FancyChair'
},
{
id: 5,
title: 'ChineseTeapot',
cuisine: 'decoration',
price: 50,
image: '/images/ChineseTeapot.png',
brand: 'rochie bobois',
availability: 'onstock',
name: 'ChineseTeapot',
tagName: 'ChineseTeapot'
},
{
id: 6,
title: 'SoftPillow',
cuisine: 'bedding',
price: 30,
image: '/images/SoftPillow.png',
brand: 'edra',
availability: 'onstock',
name: 'SoftPillow',
tagName: 'SoftPillow'
},
{
id: 7,
title: 'WoodenCasket',
cuisine: 'decoration',
price: 20,
image: '/images/WoodenCasket.png',
brand: 'kartell',
availability: 'onstock',
name: 'WoodenCasket',
tagName: 'WoodenCasket'
},
{
id: 8,
title: 'AwesomeArmChair',
cuisine: 'furniture',
price: 90,
image: '/images/AwesomeArmChair.png',
brand: 'poliform',
availability: 'onstock',
name: 'AwesomeArmchair',
tagName: 'AwesomeArmchair'
},
{
id: 9,
title: 'CoolFlower',
cuisine: 'decoration',
price: 20,
image: '/images/CoolFlower.png',
brand: 'none',
availability: 'onstock',
name: 'CoolFlower',
tagName: 'CoolFlower'
},
];

React component only rendering one item in my object

So I have a react component set up to map through all the items in my array to display them on the page. I'm importing my component onto my homepage and passing the object as a prop from the imported component. However, when I load the page, only one item from the object is being rendered. I'm not entirely sure if I'm passing my object correctly. Any help would be appreciated! Code is below.
This is my Modal component. I'm mapping through the listGroupArray that has a spread operator with my data that is being passed from the home page.
export default function ModalButton({ setData, title, arrayData, dataTitle }) {
const [show, setShow] = useState(false);
const [button, setButton] = useState("Choose...")
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const listGroupArray = [{...arrayData}]
const changeButton = e => setButton(e)
return (
<>
<h5 className="inputFont text-center">{title}</h5>
<Button style={{ backgroundColor: "black", opacity: "1", color: "white", borderColor: "red" }} variant="primary" className="w-100 mb-4 inputFont" onClick={handleShow}>
{button}
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton className="modal-bg inputFont">
{dataTitle}
</Modal.Header>
<Modal.Body className="modal-bg">
<ListGroup>
{listGroupArray.map(item => (
<ListGroup.Item key={item.id} className="modal-bg">
<Button
style={{
backgroundColor: "black",
opacity: ".8",
color: "white",
borderColor: "red",
}}
className="inputFont w-100"
name={item.name}
value={item.value}
onClick={(e) => {
setData(item.value);
changeButton(item.name);
handleClose();
}}
>
{item.name}
</Button>
</ListGroup.Item>
))}
</ListGroup>
</Modal.Body>
</Modal>
</>
);
}
This is my homepage where I'm passing the array data as an object. I'm pretty sure this is where I'm going wrong. When I load the page, the component should render all the data in the object, however it's only rendering the last data, Classics.
<Modal title="Genre"
dataTitle="Pick A Genre"
setData={setGenrelist}
arrayData={
{
id: 1,
name: "Action and Adventure",
value: "10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584"
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635"
},
{
id: 3,
name: "Sci-Fi",
value: "1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491"
},
{
id: 4,
name: "Fantasy",
value: "9744"
},
{ id: 5,
name: "Thrillers",
value: "10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972"
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424"
},
{
id: 7,
name: "Children and Family",
value: "10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783"
},
{
id: 8,
name: "Comedies",
value: "1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736"
},
{
id: 9,
name: "Documentaries",
value: "10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875"
},
{
id: 10,
name: "Dramas",
value: "11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763"
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327"
},
{
id: 12,
name: "Horror",
value: "10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585"
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675"
},
{
id: 14,
name: "Classics",
value: "10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186"
}
}
/>
screenshot of the homepage
This image shows the component only rendering one data item which is Classics. Any advice on how to get all data rendered would be greatly appreciated! Thanks!
The error is in how you referenced the arrayData and the problematic curly brackets you used on an array. In your JSX code, you have a syntax error, you are supposed to enclose arrays in curly brackets, or better still just separate them to their own variable.
Your JSX should then look something like this:
function JSX(props) {
const arrayData = [
{
id: 1,
name: "Action and Adventure",
value:
"10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584",
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635",
},
{
id: 3,
name: "Sci-Fi",
value:
"1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491",
},
{
id: 4,
name: "Fantasy",
value: "9744",
},
{
id: 5,
name: "Thrillers",
value:
"10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972",
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424",
},
{
id: 7,
name: "Children and Family",
value:
"10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783",
},
{
id: 8,
name: "Comedies",
value:
"1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736",
},
{
id: 9,
name: "Documentaries",
value:
"10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875",
},
{
id: 10,
name: "Dramas",
value:
"11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763",
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327",
},
{
id: 12,
name: "Horror",
value:
"10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585",
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675",
},
{
id: 14,
name: "Classics",
value:
"10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186",
},
];
return (
<Modal
title="Genre"
dataTitle="Pick A Genre"
setData={(data) => console.log(data)}
arrayData={arrayData}
/>
);
}
The next bug you had was in using the spread operator. While arrays are technically objects in JavaScript they can't be spread with curly braces. This [{...arrayData}] is syntactically incorrect. Instead it should be [...arrayData]. With these in place, your code should run correctly.
I made a sandbox of your code in a working state for reference, check it out here:
https://codesandbox.io/s/young-snowflake-efqwk?file=/src/ModalButton.js:877-883

Select the table rows by default based on the data in antd table

I'm new to antd and I'm stuck at one place in my project. I want to check/select the checkboxes of rows by default based on the sourcedata or data.
for example if i have the datasource as
const data =
[
{
key: "1",
name: "John",
age: 22,
chosen: true,
working: null
},
{
key : "2",
name: "Jason",
age: 23,
chosen: false,
working: 'John'
}]
So based on datasource if any object has chosen key as true, I want to check/select the checkbox of those rows by default.
I can filter out the data array depending on the chosen key has the value true or not. But how to check the checkbox by default? Is there any prop for the antd table, which will take the array of filtered data and check/select the checkbox for those rows?
I tried to check the rows using checked attribute inside getCheckboxProps but when I use that in console I get a warning saying "Warning: [antd: Table] Do not set checked or defaultChecked in getCheckboxProps. Please use selectedRowKeys instead."
Below is the code which I'm currently using.
const data =
[
{
key: "1",
name : "John",
age : 22,
chosen: true,
working: null
},
{
key : "2",
name: "Jason",
age: 23,
chosen: false,
working: "John"
}
]
const fiterSelectedRows = data.filter(row => {
return row.chosen;
});
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(
`selectedRowKeys: ${selectedRowKeys}`,
"selectedRows: ",
selectedRows
);
},
getCheckboxProps: record => {
return {
disabled: record.working != null,
name: record.working
};
}
};
<Table rowSelection={rowSelection} columns={columns} dataSource={data}/>
Notice selectedRowKeys: data.filter(item => item.chosen).map(item => item.key). selectedRowKeys contain all keys of items, all items have keys in here will be checked by default.
You need to get all items that have chosen is true.
data.filter(item => item.chosen)
// [{key: '1', name: 'John Brown', ...},
// {key: '3', name: 'Joe Black', ...},
// {key: '4', name: 'Joe Black', ...}]
// all items have chosen is true
Then get all keys of this array.
data.filter(item => item.chosen).map(item => item.key)
// ['1', '2', '3']
// all keys of items have chosen is true
Exmample code:
Data
const data = [{
key: '1',
name: 'John Brown',
age: 32,
chosen: true,
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: 'Jim Green',
age: 42,
chosen: false,
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: 'Joe Black',
age: 32,
chosen: true,
address: 'Sidney No. 1 Lake Park',
}, {
key: '4',
name: 'Disabled User',
age: 99,
chosen: true,
address: 'Sidney No. 1 Lake Park',
}];
Datatable
class App extends React.Component {
state = {
selectedRowKeys: data.filter(item => item.chosen).map(item => item.key), // Check here to configure the default column
loading: false,
};
start = () => {
this.setState({ loading: true });
// ajax request after empty completing
setTimeout(() => {
this.setState({
selectedRowKeys: [],
loading: false,
});
}, 1000);
};
onSelectChange = selectedRowKeys => {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.setState({ selectedRowKeys });
};
render() {
const { loading, selectedRowKeys } = this.state;
const rowSelection = {
selectedRowKeys,
onChange: this.onSelectChange,
};
const hasSelected = selectedRowKeys.length > 0;
return (
<div>
<div style={{ marginBottom: 16 }}>
<Button type="primary" onClick={this.start} disabled={!hasSelected} loading={loading}>
Reload
</Button>
<span style={{ marginLeft: 8 }}>
{hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
</span>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} />
</div>
);
}
}
The author above said all the right things, I decided to share my experience. I have an array of objects with no key field (hello backend). Initially I filtered this array by a condition (depends on your task), for example, that the coin_symbol field === "WBNB". After filtering, I immediately use map to create a new array. Don't forget to make local state.
const [selectedRowKeys, setSelectedRowKeys] = useState()
setSelectedRowKeys(dashboardData?.filter(i => i.coin_symbol === 'WBNB').map(i => i.id))
Then, after digging in the table props, I saw a props defaultSelectedRowKeys, which takes an array. Further everything is simple - to this props assign value to our new array.
const rowSelection = { defaultSelectedRowKeys: selectedRowKeys, ...otherProps (like onChange, getCheckboxProps, etc.)
Another important thing - if you have, as I do, the data from the server go long, better not render a table, but rather, for example, some kind of loading text or a slider.
selectedRowKeys ? <YourTable dataSource={yourData} rowSelection={rowSelection}/> : <Loader/>
I hope it helps someone! (~ ̄▽ ̄)~

Resources