Issue while using react-picky select menu - reactjs

I have recently downloaded the react-picky and have used it inside a map function to loop through my dynamic data. In the picky i have set multiselect as true.
How ever on the onchange function am getting only the currently selected value and not the list of values selected for picky.
The issue am facing is in the case of multiselect where the value will be a single object containing the current selected item rather than the list of items selected. Could you please help me with the issue. I have tried every possible solution and it does not seem to work.Any help would be really appreciated as am stuck in the issue for sometime.
const sectorsData = [
{
name: "Technology",
options: [
{
id: "1",
name: "AI & Analytics"
},
{
id: "2",
name: "Robotics"
},
{
id: "3",
name: "IoT"
}
]
},
{
name: "Sector",
options: [
{
id: "1",
name: "Automotive"
},
{
id: "2",
name: "Oil and gas"
},
{
id: "3",
name: "Consumer Products"
}
]
},
{
name: "Accounts",
options: [
{
id: "1",
name: "Alphabet Inc."
},
{
id: "2",
name: "General Motors Company"
},
{
id: "3",
name: "Consumer Products"
},
{
id: "4",
name: "State Street Corporation"
}
]
},
{
name: "Region",
options: [
{
id: "1",
name: "Canada Region"
},
{
id: "2",
name: "Central"
},
{
id: "3",
name: "FSO Americas"
},
{
id: "4",
name: "Latam North"
},
{
id: "5",
name: "Latam South"
}
]
}
];
const App = props => {
const [assetsAddedState, setAssetsAddedState] = React.useState({
selectedItems: []
});
const selectedOption = (name, value) => {
setAssetsAddedState(prev => {
return { ...prev, [name]: value };
});
};
return (
<form className="create-work-form-container" noValidate autoComplete="off">
{sectorsData.map((selectItem, i) => (
<Picky
value={assetsAddedState[selectItem.name]}
onChange={selectedOption.bind(this, selectItem.name)}
options={selectItem.options}
placeholder={selectItem.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={selectItem.name}
/>
))}
</form>
);
};
value should be returning the multiple values user has selected.

See if this is working for you:
Working example on CodeSandbox:
https://codesandbox.io/s/react-pickyanswerso-yp02j
import React from "react";
import { render } from "react-dom";
import Picky from "react-picky";
import "react-picky/dist/picky.css";
const sector1 = {
name: "Technology",
options: [
{
id: "1",
name: "AI & Analytics"
},
{
id: "2",
name: "Robotics"
},
{
id: "3",
name: "IoT"
}
]
};
const sector2 = {
name: "Sector",
options: [
{
id: "4",
name: "Automotive"
},
{
id: "5",
name: "Oil and gas"
},
{
id: "6",
name: "Consumer Products"
}
]
};
const sector3 = {
name: "Accounts",
options: [
{
id: "7",
name: "Alphabet Inc."
},
{
id: "8",
name: "General Motors Company"
},
{
id: "9",
name: "Consumer Products"
},
{
id: "10",
name: "State Street Corporation"
}
]
};
const sector4 = {
name: "Region",
options: [
{
id: "11",
name: "Canada Region"
},
{
id: "12",
name: "Central"
},
{
id: "13",
name: "FSO Americas"
},
{
id: "14",
name: "Latam North"
},
{
id: "15",
name: "Latam South"
}
]
};
const App = props => {
// const [assetsAddedState, setAssetsAddedState] = React.useState([]);
const [selected1, setSelected1] = React.useState([]);
const [selected2, setSelected2] = React.useState([]);
const [selected3, setSelected3] = React.useState([]);
const [selected4, setSelected4] = React.useState([]);
const selectedOption1 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected1(value);
};
const selectedOption2 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected2(value);
};
const selectedOption3 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected3(value);
};
const selectedOption4 = value => {
console.log("VAlue: " + JSON.stringify(value));
setSelected4(value);
};
return (
<form className="create-work-form-container" noValidate autoComplete="off">
<Picky
value={selected1}
onChange={selectedOption1}
options={sector1.options}
placeholder={sector1.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector1.name}
/>
<Picky
value={selected2}
onChange={selectedOption2}
options={sector2.options}
placeholder={sector2.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector2.name}
/>
<Picky
value={selected3}
onChange={selectedOption3}
options={sector3.options}
placeholder={sector3.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector3.name}
/>
<Picky
value={selected4}
onChange={selectedOption4}
options={sector4.options}
placeholder={sector4.name}
numberDisplayed={1}
valueKey="id"
labelKey="name"
multiple={true}
includeSelectAll={true}
includeFilter={true}
dropdownHeight={600}
className="multiSelectControl "
name={sector4.name}
/>
</form>
);
};
render(<App />, document.getElementById("root"));

Related

My multi select is not working, and I can't save data into database

I tried to make a function that add list of country. But it's not working at the last input (Những ngôn ngữ dịch. I can't save it into database to. What should I do?
I tried to add as much as possible country on the last input. But it didn't show. Here are my code:
import '../../css/style.css';
import { useEffect } from "react";
import { useState, useSelector } from "react";
import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base";
import Select from 'react-select'
import { Const_Libs } from "../libs/Const_Libs";
const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props;
const [ngonNgu, setNgonNgu] = useState({
language_name: '',
main_lang: '',
title_lang: '',
describe_lang: '',
author_lang: '',
rate_lang: '',
reviews_lang: '',
// translate_list: []
translate_list: []
});
function SelectMainLanguage() {
const [selectedOption, setSelectedOption] = useState({});
const options = [
{ value: 'Vietnamese', label: 'Vietnamese' },
{ value: 'English', label: 'English' },
{ value: 'Chinese', label: 'Chinese' },
{ value: 'Japanese', label: 'Japanese' },
{ value: 'German', label: 'German' },
];
const handleChangeOption = () => {
return setSelectedOption;
}
useEffect(() => {
if (selectedOption.value) {
console.log(selectedOption)
setNgonNgu({ ...ngonNgu, main_lang: selectedOption.value })
}
}, [selectedOption])
// {console.log(selectedOption)}
return (
<Select className={`col-12 o-languages`}
value={ngonNgu.main_lang ? { value: ngonNgu.main_lang, label: ngonNgu.main_lang } : { value: "Chọn ngôn ngữ chính", label: "Chọn ngôn ngữ chính" }}
onChange={handleChangeOption()}
options={options} />
)
}
function SelectTransLanguage() {
const [selectedOption, setSelectedOption] = useState({});
const options = [
{ value: "AF", label: "Afghanistan" },
{ value: "AL", label: "Albania" },
{ value: "DZ", label: "Algeria" },
{ value: "AS", label: "American Samoa" },
{ value: "AD", label: "Andorra" },
{ value: "AO", label: "Angola" },
{ value: "AI", label: "Anguilla" },
{ value: "AQ", label: "Antarctica" },
{ value: "AG", label: "Antigua And Barbuda" },
{ value: "AR", label: "Argentina" },
{ value: "AM", label: "Armenia" },
{ value: "AW", label: "Aruba" },
{ value: "AU", label: "Australia" },
{ value: "AT", label: "Austria" },
{ value: "AZ", label: "Azerbaijan" },
{ value: "BS", label: "Bahamas The" },
{ value: "BH", label: "Bahrain" },
{ value: "BD", label: "Bangladesh" },
{ value: "BB", label: "Barbados" },
{ value: "BY", label: "Belarus" },
{ value: "BE", label: "Belgium" },
{ value: "BZ", label: "Belize" },
{ value: "BJ", label: "Benin" },
{ value: "BM", label: "Bermuda" },
{ value: "BT", label: "Bhutan" },
{ value: "BO", label: "Bolivia" },
{ value: "BA", label: "Bosnia and Herzegovina" },
{ value: "BW", label: "Botswana" },
{ value: "BV", label: "Bouvet Island" },
{ value: "BR", label: "Brazil" },
{ value: "IO", label: "British Indian Ocean Territory" },
{ value: "BN", label: "Brunei" },
{ value: "BG", label: "Bulgaria" },
{ value: "BF", label: "Burkina Faso" },
{ value: "BI", label: "Burundi" },
{ value: "KH", label: "Cambodia" },
{ value: "CM", label: "Cameroon" },
{ value: "CA", label: "Canada" },
{ value: "CV", label: "Cape Verde" },
{ value: "KY", label: "Cayman Islands" },
{ value: "CF", label: "Central African Republic" },
{ value: "TD", label: "Chad" },
{ value: "CL", label: "Chile" },
{ value: "CN", label: "China" },
{ value: "CX", label: "Christmas Island" },
{ value: "CC", label: "Cocos (Keeling) Islands" },
{ value: "CO", label: "Colombia" },
{ value: "KM", label: "Comoros" },
{ value: "CG", label: "Congo" },
{ value: "CD", label: "Congo The Democratic Republic Of The" },
{ value: "CK", label: "Cook Islands" },
{ value: "CR", label: "Costa Rica" },
{ value: "CI", label: "Cote D'Ivoire (Ivory Coast)" },
{ value: "HR", label: "Croatia (Hrvatska)" },
{ value: "CU", label: "Cuba" },
{ value: "CY", label: "Cyprus" },
{ value: "CZ", label: "Czech Republic" },
{ value: "DK", label: "Denmark" },
{ value: "DJ", label: "Djibouti" },
{ value: "DM", label: "Dominica" },
{ value: "DO", label: "Dominican Republic" },
{ value: "TP", label: "East Timor" },
{ value: "EC", label: "Ecuador" },
{ value: "EG", label: "Egypt" },
{ value: "SV", label: "El Salvador" },
{ value: "GQ", label: "Equatorial Guinea" },
{ value: "ER", label: "Eritrea" },
{ value: "EE", label: "Estonia" },
{ value: "ET", label: "Ethiopia" },
{ value: "XA", label: "External Territories of Australia" },
{ value: "FK", label: "Falkland Islands" },
{ value: "FO", label: "Faroe Islands" },
{ value: "FJ", label: "Fiji Islands" },
{ value: "FI", label: "Finland" },
{ value: "FR", label: "France" },
{ value: "GF", label: "French Guiana" },
{ value: "PF", label: "French Polynesia" },
{ value: "TF", label: "French Southern Territories" },
{ value: "GA", label: "Gabon" },
{ value: "GM", label: "Gambia The" },
{ value: "GE", label: "Georgia" },
{ value: "DE", label: "Germany" },
{ value: "GH", label: "Ghana" },
{ value: "GI", label: "Gibraltar" },
{ value: "GR", label: "Greece" },
{ value: "GL", label: "Greenland" },
{ value: "GD", label: "Grenada" },
{ value: "GP", label: "Guadeloupe" },
{ value: "GU", label: "Guam" },
{ value: "GT", label: "Guatemala" },
{ value: "XU", label: "Guernsey and Alderney" },
{ value: "GN", label: "Guinea" },
{ value: "GW", label: "Guinea-Bissau" },
{ value: "GY", label: "Guyana" },
{ value: "HT", label: "Haiti" },
{ value: "HM", label: "Heard and McDonald Islands" },
{ value: "HN", label: "Honduras" },
{ value: "HK", label: "Hong Kong S.A.R." },
{ value: "HU", label: "Hungary" },
{ value: "IS", label: "Iceland" },
{ value: "IN", label: "India" },
{ value: "ID", label: "Indonesia" },
{ value: "IR", label: "Iran" },
{ value: "IQ", label: "Iraq" },
{ value: "IE", label: "Ireland" },
{ value: "IL", label: "Israel" },
{ value: "IT", label: "Italy" },
{ value: "JM", label: "Jamaica" },
{ value: "JP", label: "Japan" },
{ value: "XJ", label: "Jersey" },
{ value: "JO", label: "Jordan" },
{ value: "KZ", label: "Kazakhstan" },
{ value: "KE", label: "Kenya" },
{ value: "KI", label: "Kiribati" },
{ value: "KP", label: "Korea North" },
{ value: "KR", label: "Korea South" },
{ value: "KW", label: "Kuwait" },
{ value: "KG", label: "Kyrgyzstan" },
{ value: "LA", label: "Laos" },
{ value: "LV", label: "Latvia" },
{ value: "LB", label: "Lebanon" },
{ value: "LS", label: "Lesotho" },
{ value: "LR", label: "Liberia" },
{ value: "LY", label: "Libya" },
{ value: "LI", label: "Liechtenstein" },
{ value: "LT", label: "Lithuania" },
{ value: "LU", label: "Luxembourg" },
{ value: "MO", label: "Macau S.A.R." },
{ value: "MK", label: "Macedonia" },
{ value: "MG", label: "Madagascar" },
{ value: "MW", label: "Malawi" },
{ value: "MY", label: "Malaysia" },
{ value: "MV", label: "Maldives" },
{ value: "ML", label: "Mali" },
{ value: "MT", label: "Malta" },
{ value: "XM", label: "Man (Isle of)" },
{ value: "MH", label: "Marshall Islands" },
{ value: "MQ", label: "Martinique" },
{ value: "MR", label: "Mauritania" },
{ value: "MU", label: "Mauritius" },
{ value: "YT", label: "Mayotte" },
{ value: "MX", label: "Mexico" },
{ value: "FM", label: "Micronesia" },
{ value: "MD", label: "Moldova" },
{ value: "MC", label: "Monaco" },
{ value: "MN", label: "Mongolia" },
{ value: "MS", label: "Montserrat" },
{ value: "MA", label: "Morocco" },
{ value: "MZ", label: "Mozambique" },
{ value: "MM", label: "Myanmar" },
{ value: "NA", label: "Namibia" },
{ value: "NR", label: "Nauru" },
{ value: "NP", label: "Nepal" },
{ value: "AN", label: "Netherlands Antilles" },
{ value: "NL", label: "Netherlands The" },
{ value: "NC", label: "New Caledonia" },
{ value: "NZ", label: "New Zealand" },
{ value: "NI", label: "Nicaragua" },
{ value: "NE", label: "Niger" },
{ value: "NG", label: "Nigeria" },
{ value: "NU", label: "Niue" },
{ value: "NF", label: "Norfolk Island" },
{ value: "MP", label: "Northern Mariana Islands" },
{ value: "NO", label: "Norway" },
{ value: "OM", label: "Oman" },
{ value: "PK", label: "Pakistan" },
{ value: "PW", label: "Palau" },
{ value: "PS", label: "Palestinian Territory Occupied" },
{ value: "PA", label: "Panama" },
{ value: "PG", label: "Papua new Guinea" },
{ value: "PY", label: "Paraguay" },
{ value: "PE", label: "Peru" },
{ value: "PH", label: "Philippines" },
{ value: "PN", label: "Pitcairn Island" },
{ value: "PL", label: "Poland" },
{ value: "PT", label: "Portugal" },
{ value: "PR", label: "Puerto Rico" },
{ value: "QA", label: "Qatar" },
{ value: "RE", label: "Reunion" },
{ value: "RO", label: "Romania" },
{ value: "RU", label: "Russia" },
{ value: "RW", label: "Rwanda" },
{ value: "SH", label: "Saint Helena" },
{ value: "KN", label: "Saint Kitts And Nevis" },
{ value: "LC", label: "Saint Lucia" },
{ value: "PM", label: "Saint Pierre and Miquelon" },
{ value: "VC", label: "Saint Vincent And The Grenadines" },
{ value: "WS", label: "Samoa" },
{ value: "SM", label: "San Marino" },
{ value: "ST", label: "Sao Tome and Principe" },
{ value: "SA", label: "Saudi Arabia" },
{ value: "SN", label: "Senegal" },
{ value: "RS", label: "Serbia" },
{ value: "SC", label: "Seychelles" },
{ value: "SL", label: "Sierra Leone" },
{ value: "SG", label: "Singapore" },
{ value: "SK", label: "Slovakia" },
{ value: "SI", label: "Slovenia" },
{ value: "XG", label: "Smaller Territories of the UK" },
{ value: "SB", label: "Solomon Islands" },
{ value: "SO", label: "Somalia" },
{ value: "ZA", label: "South Africa" },
{ value: "GS", label: "South Georgia" },
{ value: "SS", label: "South Sudan" },
{ value: "ES", label: "Spain" },
{ value: "LK", label: "Sri Lanka" },
{ value: "SD", label: "Sudan" },
{ value: "SR", label: "Suriname" },
{ value: "SJ", label: "Svalbard And Jan Mayen Islands" },
{ value: "SZ", label: "Swaziland" },
{ value: "SE", label: "Sweden" },
{ value: "CH", label: "Switzerland" },
{ value: "SY", label: "Syria" },
{ value: "TW", label: "Taiwan" },
{ value: "TJ", label: "Tajikistan" },
{ value: "TZ", label: "Tanzania" },
{ value: "TH", label: "Thailand" },
{ value: "TG", label: "Togo" },
{ value: "TK", label: "Tokelau" },
{ value: "TO", label: "Tonga" },
{ value: "TT", label: "Trinidad And Tobago" },
{ value: "TN", label: "Tunisia" },
{ value: "TR", label: "Turkey" },
{ value: "TM", label: "Turkmenistan" },
{ value: "TC", label: "Turks And Caicos Islands" },
{ value: "TV", label: "Tuvalu" },
{ value: "UG", label: "Uganda" },
{ value: "UA", label: "Ukraine" },
{ value: "AE", label: "United Arab Emirates" },
{ value: "GB", label: "United Kingdom" },
{ value: "US", label: "United States" },
{ value: "UM", label: "United States Minor Outlying Islands" },
{ value: "UY", label: "Uruguay" },
{ value: "UZ", label: "Uzbekistan" },
{ value: "VU", label: "Vanuatu" },
{ value: "VA", label: "Vatican City State (Holy See)" },
{ value: "VE", label: "Venezuela" },
{ value: "VN", label: "Vietnam" },
{ value: "VG", label: "Virgin Islands (British)" },
{ value: "VI", label: "Virgin Islands (US)" },
{ value: "WF", label: "Wallis And Futuna Islands" },
{ value: "EH", label: "Western Sahara" },
{ value: "YE", label: "Yemen" },
{ value: "YU", label: "Yugoslavia" },
{ value: "ZM", label: "Zambia" },
{ value: "ZW", label: "Zimbabwe" }
];
const handleChangeOption = () => {
return setSelectedOption;
}
useEffect(() => {
if (selectedOption.value) {
console.log(selectedOption)
setNgonNgu({ ...ngonNgu, translate_list: selectedOption.value })
}
}, [selectedOption])
{console.log(selectedOption)}
return (
<Select className={`col-12 o-languages`}
isMulti
value={ngonNgu.translate_list ? { value: ngonNgu.translate_list, label: ngonNgu.translate_list } : { value: "Chọn những ngôn ngữ dịch", label: "Chọn những ngôn ngữ dịch" }}
onChange={handleChangeOption()}
options={options} />
)
}
const handleSubmit = () => {
let arr = [{
nameLanguage: ngonNgu.language_name,
mainLanguage: ngonNgu.main_lang,
titleLanguage: ngonNgu.title_lang,
descriptionLanguage: ngonNgu.describe_lang,
authorLanguage: ngonNgu.author_lang,
rateLanguage: ngonNgu.rate_lang,
reviewsLanguage: ngonNgu.reviews_lang,
transLanguage: ngonNgu.translate_list
}]
ajaxCallPost(`save-lang`, arr).then(rs => {
resetData()
handleGetLanguage();
Const_Libs.TOAST.success("Thêm thành công")
})
}
const resetData = () => {
setNgonNgu({
language_name: '',
main_lang: '',
title_lang: '',
describe_lang: '',
author_lang: '',
rate_lang: '',
reviews_lang: '',
translate_list: []
})
}
return (
<>
<button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}>
Thêm
</button>
<div>
<div className="modal fade" id="myModalAddNgonNgu">
<div className="modal-dialog modal-dialog-centered" style={{ minWidth: '700px' }}>
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">Thêm ngôn ngữ</h4>
<button type="button" className="btn-close" data-bs-dismiss="modal" />
</div>
<div className="modal-body">
<form>
<div className="col">
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tên ngôn ngữ</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tên ngôn ngữ...."
value={ngonNgu.language_name}
onChange={(e) => setNgonNgu({ ...ngonNgu, language_name: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tiêu đề</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tiêu đề...."
value={ngonNgu.title_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, title_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Mô tả</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập mô tả...."
value={ngonNgu.describe_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, describe_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tác giả</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập tác giả (VD: Author)"
value={ngonNgu.author_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, author_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Đánh giá</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập đánh giá (VD: Rate)"
value={ngonNgu.rate_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, rate_lang: e.target.value })}
/>
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Lượt đánh giá</label>
<input type="text"
className="form-control" id="name-campaign"
placeholder="Nhập lượt đánh giá (VD: reviews)"
value={ngonNgu.reviews_lang}
onChange={(e) => setNgonNgu({ ...ngonNgu, reviews_lang: e.target.value })}
/>
</div>
</div>
<div className="col">
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Ngôn ngữ chính</label>
<SelectMainLanguage />
</div>
<div className="row-2">
<label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Những ngôn ngữ dịch</label>
<SelectTransLanguage />
</div>
</div>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button>
<button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</>
);
}
export default ModalAddNgonNgu;
The backend is OK, so the problem is this thing. Can you show me the mistake? Thank you
You should never define a component inside another component.
Move both SelectMainLanguage and SelectTransLanguage out of ModalAddNgonNgu.
Then connect these two components and ModalAddNgonNgu with props.
Like this:
const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props; ....
... rest of the component
} // end of ModalAddNgonNgu definition
function SelectTransLanguage({setNgonNgu}) { // setNgonNgu comes from ModalAddNgonNgu
const [selectedOption, setSelectedOption] = useState({}) ....
}

I am trying to filter array of objects (courses) with array of unique data (tag) using checkbox button using react hooks

I am trying to filter array of objects (courses) with array of unique data (tag) using
checkbox button using react hooks. Its not working. please help me to add checked inside
<input type="checkbox" checked={ } />
Its working fine if input type="radio" but not working for type="checkbox"
import { useState } from "react";
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];
const App = () => {
const [checked, setChecked] = useState("all");
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (tag: any) => {
setChecked(tag);
if (tag !== "all") {
const filteredItems = courses.filter((item) => item.tag === tag);
setFilterData(filteredItems);
} else {
setFilterData(courses);
}
};
return (
<div>
<input
type="checkbox"
checked={checked === "all"}
onChange={() => handleFilterItems("all")}
/>{" "}
All
{uniqueTags.map((tag, index) => (
<div key={index}>
<input
type="checkbox"
checked={checked === tag}
onChange={() => handleFilterItems(tag)}
/>
{tag}
</div>
))}
{filterData.map((course) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</div>
);
};
export default App;
the checkbox filtering logic needs some fix. Please find my solution - https://codesandbox.io/s/intelligent-chaplygin-0ot56e?file=/src/App.js
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" }
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];
const App = () => {
const [checked, setChecked] = useState(uniqueTags);
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (event, tag) => {
if (event.target.checked) {
if (tag === "all") {
setFilterData(courses);
setChecked(uniqueTags);
} else {
setChecked([...checked, tag]);
const addedData = courses.filter((item) => item.tag === tag);
setFilterData([...filterData, ...addedData]);
}
} else {
if (tag === "all") {
setFilterData([]);
setChecked([]);
} else {
const removedData = filterData.filter((item) => item.tag !== tag);
setFilterData(removedData);
setChecked(checked.filter((item) => item !== tag));
}
}
};
return (
<div>
<input
type="checkbox"
checked={checked.length === uniqueTags.length}
onChange={(event) => handleFilterItems(event, "all")}
/>{" "}
All
{uniqueTags.map((tag, index) => (
<div key={index}>
<input
type="checkbox"
checked={checked.includes(tag)}
onChange={(event) => handleFilterItems(event, tag)}
/>
{tag}
</div>
))}
{filterData.map((course) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</div>
);
};

I am trying to filter array of objects (courses) with array of unique data (tag) using checkbox button using react hooks. Its not working

I am trying to filter array of objects (courses) with array of unique data (tag) using checkbox button using react hooks. Its not working. At start it shows all the list, but when I select tag one by one, it gets added below the list. You should see all the list first but after selecting tag it should show perticular tag data only. How can I achieve this?
Please find my code below:
import React, { useState } from "react";
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];
const App = () => {
const [checked, setChecked] = useState<any>([]);
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (event: any, tag: any) => {
setFilterData([]);
if (event.target.checked) {
setChecked([...checked, tag]);
const addedData = courses.filter((item) => item.tag === tag);
setFilterData([...filterData, ...addedData]);
} else {
const removedData = filterData.filter((item) => item.tag !== tag);
setFilterData(removedData);
setChecked(checked.filter((item: any) => item !== tag));
}
};
return (
<div style={{ textAlign: "center" }}>
{uniqueTags.map((tag, index) => (
<label key={index}>
<input
type="checkbox"
checked={checked.includes(tag)}
onChange={(event) => handleFilterItems(event, tag)}
/>
{tag}
</label>
))}
<hr />
{filterData.map((course) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</div>
);
};
export default App;
You need to change two lines:
import React, { useState } from "react";
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];
const App = () => {
const [checked, setChecked] = useState([]);
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (event: any, tag: any) => {
setFilterData([]);
if (event.target.checked) {
setChecked([...checked, tag]);
const addedData = courses.filter((item) => item.tag === tag);
setFilterData([...addedData]); <------------ this line
} else {
const removedData = courses.filter((item) => item.tag !== tag); <--this line
setFilterData(removedData);
setChecked(checked.filter((item: any) => item !== tag));
}
};
return (
<div style={{ textAlign: "center" }}>
{uniqueTags.map((tag, index) => (
<label key={index}>
<input
type="checkbox"
checked={checked.includes(tag)}
onChange={(event) => handleFilterItems(event, tag)}
/>
{tag}
</label>
))}
<hr />
{filterData.map((course) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</div>
);
};
export default App;
Edited: use the useEffect hook
import React, { useState } from "react";
const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];
const App = () => {
const [checked, setChecked] = useState([]);
const [filterData, setFilterData] = useState(courses);
const handleFilterItems = (event: any, tag: any) => {
setFilterData([]);
if (event.target.checked) {
setChecked([...checked, tag]);
//const addedData = courses.filter((item) => item.tag === tag);
//setFilterData([...addedData]);
} else {
//const removedData = courses.filter((item) => item.tag !== tag);
//setFilterData(removedData);
setChecked(checked.filter((item: any) => item !== tag));
}
};
React.useEffect(() => {
if(checked.length == 0){
setFilterData([...courses])
}else{
let filtered = courses.filter((el:any) => checked.includes(el.tag))
setFilterData([...filtered])
}
},[checked])
return (
<div style={{ textAlign: "center" }}>
{uniqueTags.map((tag, index) => (
<label key={index}>
<input
type="checkbox"
checked={checked.includes(tag)}
onChange={(event) => handleFilterItems(event, tag)}
/>
{tag}
</label>
))}
<hr />
{filterData.map((course) => (
<li key={course.id}>
{course.id}-{course.course}-{course.tag}
</li>
))}
</div>
);
};
export default App;

Changing object in array using useState

I'd like to change each Data[0].datasets label using the array in Axisstate
I tried to put Axis's label to each Data label but i doesn't work, and it's not what i expected it would be.
both are changed to as same as the last one that i write.
and I'm trying to add more elements to datasets using the AxisHandler function to use push.
and It's doesn't change as soon as i click AxisUpdatefunction.
I'd like to know why it happens and what i should do .
Thank you in advance.
my code is like this:
import React, { useState } from "react";
import { Data, AppendData } from "./Data";
const Changeable = () => {
const [Axis, setAxis] = useState([]);
const changeHandler = index => e => {
setAxis(Axis =>
Axis.map((el, i) => (i === index ? { ...el, label: e.target.value } : el))
);
};
const AxisHandler = e => {
setAxis([
...Axis,
{
label: "",
data: "",
backgroundColor: "",
},
]);
Data[0].datasets.push(AppendData);
};
const AxisUpdate = () => {
if (Data[0].datasets[1].label) {
Data[0].datasets[1].label = Axis[0].label;
}
if (Data[0].datasets[2].label) {
Data[0].datasets[2].label = Axis[1].label;
}
};
return (
<div>
<button onClick={AxisHandler}>addAxis</button>
<>
{Axis.map((data, index) => (
<>
<input
placeholder={index + 1}
type="text"
onChange={changeHandler(index)}
/>
</>
))}
</>
<button onClick={AxisUpdate}>changeLabel</button>
<br />
<h1>{Data[0].datasets[0].label}</h1>
<br />
<h1>{Data[0].datasets[1] && Data[0].datasets[1].label}</h1>
<br />
<h1>{Data[0].datasets[2] && Data[0].datasets[2].label}</h1>
</div>
);
};
export default Changeable;
Data and AppendData
export const defaultLabels = [
"0",
"0",
"0",
"0",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
];
export const defaultDatas = [
13000, 11000, 9000, 4000, 14000, 16000, 20000, 11000, 14000, 11200, 12000,
12000,
];
export const defaultBackgroundColor = [
"#ff6385e1",
"#36a3ebf0",
"#ffcf56c8",
"#4bc0c0be",
"#9966ffa2",
"#ffa040b2",
];
export let AppendData = {
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
};
export let Data = [
{
labels: defaultLabels,
datasets: [
{
label: "First",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
}, ///1번
{
labels: defaultLabels,
datasets: [
{
label: "Second",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
{
labels: defaultLabels,
datasets: [
{
label: "Third",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
]; ///2번

React JS, When clicked one option, other options are also being selected

Below is Options component It generates bunch of options The problem is that when I click One option Others are also being selected. I know why this is happening but I couldnt solve it
const InterestGenerator = () => {
const interest_emojis = [
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
];
const [selected, setSelected] = useState(false);
const handleClick = (e) => {
selected ? setSelected(false) : setSelected(true);
};
return (
<div className="interests_options">
{interest_emojis.map((interest) => {
return (
<div
className={`interest ${selected ? " interest_selected" : ""}`}
onClick={handleClick}
>
{!selected && (
<img
className="interest_emoji"
src={require("../assets/emoji_" + interest.name + ".png")}
alt="comedy_emoji"
/>
)}
{selected && <DoneIcon />}
<span>{interest.name}</span>
</div>
);
})}
</div>
);
};
export default InterestGenerator;
enter image description here
As you can see you have a single selected state in the component. Hence even if you click once it's set for everybody.
The solution would be to have a component each having their own state that is doing what you're doing and rendering a list of those components.
Something like this will work :
This is the solo component :
const interestEmojiComponent = ({name})=>{
const [selected, setSelected] = useState(false);
const handleClick = (e) => {
selected ? setSelected(false) : setSelected(true);
};
return (
<div
className={`interest ${selected ? " interest_selected" : ""}`}
onClick={handleClick}
>
{!selected && (
<img
className="interest_emoji"
src={require("../assets/emoji_" + name + ".png")}
alt="comedy_emoji"
/>
)}
{selected && <DoneIcon />}
<span>{name}</span>
</div>
);
}
And this is the generator Component :
const InterestGenerator = () => {
const interest_emojis = [
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
{ name: "Comedy" },
];
return(
<div className="interests_options">
{interest_emojis.map((interest) => <InterestEmojiComponent name={interest.name}/>)}
</div>
)
}
You are using just one selected state for all options which lead to your unexpected behavior. The solution here is to keep the selected state for each option
const [interest_emojis, set_interest_emojis] = useState([
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false },
{ name: "Comedy", selected: false }
]);
const handleClick = (index) => {
const arr = [...interest_emojis];
arr[index].selected = !arr[index].selected;
set_interest_emojis(arr);
};
Demo

Resources