Getting the newly selected option value with React Select - reactjs

I have my select:
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={() => getSelect(mySelect)}
/>
I have my function:
function getSelect(val) {
console.log(val.current.props.value["value"])
}
This logs the previous value, I understand why this happens but I can't think of another way to attempt this. Is there something similar to afterChange?

To get the current value, you should be using the value from the onChange instead. You don't need ref for this
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={(value) => getSelect(value)}
/>
function getSelect(val) {
console.log(val)
}

It':
val.current.value
Not:
val.current.props.value
And since you are using ref so you don't need to send it throw parameter to handleChange function:
const mySelect = React.useRef(null);
function handleChange() {
if (mySelect.current) {
console.log(mySelect.current.value);
}
}
......
<Select
options={[
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" },
{ value: "5", label: "5" },
{ value: "6", label: "6" },
]}
name="mySelect"
ref={mySelect}
instanceId="mySelect"
defaultValue=""
onChange={handleChange}
/>

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({}) ....
}

How can I add the first to the array in useState in React?

I have an array object called tempArr.
When I run a function called fetchLifeCycle, i want to act setPickerItems(tempArr); is mandatory first, and then setPickerItems([...tempArr, { label: 'Not selected', value: "NONE" }]) .
As a result, { label: 'not selected', value: "NONE" } was added at the end.
But I want to add that object to the first object of pickerItems. How do I do that?
this is my code
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const [pickerItems, setPickerItems] = useState([])
const fetchLifeCycle = () => {
setPickerItems(tempArr);
setPickerItems([...tempArr, { label: '선택안함', value: "NONE" }])
}
expected answer
pickerItems = [
{ label: '선택안함', value: "NONE" }
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const updated = [{ label: '선택안함', value: "NONE" }, ...tempArr]
console.log('updated', updated)
You just have to reverse the order:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
You can put the new item first, then spread the existing array:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
Just simple:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])

Pushing items from first array of objects to another array of objects

defaultParameterTypes = [] // this is my empty array
const propsArray = this.props.device.deviceProperties.defaultParameterTypes;
const defaultParameterTypes = this.state.deviceSettings.defaultParameterTypes;
when i checked on checkbox i want to push into my defaultParameterTypes array the object but the case is
when the type is repeated dont push it twice.
"propsArray": "[{'name': '1','type': '11'}, {'name': '2','type': '22'}, {'name': '3','type': '11'}, {'name': '4','type': '11'}, {'name': '5','type': '22'}, {'name': '6','type': '22'}, {'name': '7','type': '22'}]",
i want to make like loop and check if it is not found in defaultEmptyArray and push it if not found
but i dont need the type to be repeated in mydefaultarray
Simple way would be to create a map of the types seen in the array and reduce your input array into it, then get the array of values from the map you created.
const data = [
{ name: "1", type: "11" },
{ name: "2", type: "22" },
{ name: "3", type: "11" },
{ name: "4", type: "11" },
{ name: "5", type: "22" },
{ name: "6", type: "22" },
{ name: "7", type: "22" }
];
// reduce array into map of type => { name, type }
// then get the object values array
const reducedData = Object.values(
data.reduce((acc, { name, type}) => {
if (!acc[type]) acc[type] = { name, type }; // if not seen type, store
return acc;
}, {})
);
console.log(reducedData)
Expand on this concept to create a function that takes two arrays and processes the second into the first.
const data = [
{ name: "1", type: "11" },
{ name: "2", type: "22" },
{ name: "3", type: "44" },
{ name: "4", type: "11" },
{ name: "5", type: "22" },
{ name: "6", type: "33" },
{ name: "7", type: "22" }
];
const data2 = [
{ name: "1", type: "33" },
{ name: "2", type: "22" },
{ name: "3", type: "66" },
{ name: "4", type: "11" },
{ name: "5", type: "22" },
{ name: "6", type: "44" },
{ name: "7", type: "22" }
];
const data3 = [
{ name: "1", type: "66" },
{ name: "2", type: "22" },
{ name: "3", type: "33" },
{ name: "4", type: "11" },
{ name: "5", type: "55" },
{ name: "6", type: "11" },
{ name: "7", type: "44" }
];
const reduceData = (currentArray = [], newArray = []) => {
const mapFn = (acc, { name, type }) => {
if (!acc[type]) acc[type] = { name, type }; // if not seen type, store
return acc;
};
const createMap = array => array.reduce(mapFn, {});
return Object.values(newArray.reduce(mapFn, createMap(currentArray)));
};
const reducedData = reduceData(data, data2);
const reducedData1 = reduceData(reducedData, data3);
console.log(reducedData);
console.log(reducedData1);
let hasValue = (arr, obj) => arr && arr.filter(item => item.type == obj.type).length
let result = propsArray.reduce((acc, curr) => {
if (hasValue(acc, curr)) {
return acc;
} else {
return [...acc, curr]
}
}, []);
will give u an array with all the elements where the type property is unique..
hope this is what ur expected result..
let result = propsArray.reduce((acc, curr) => {
if (hasValue(acc, curr)) {
return [...acc, { name: curr.name }];
} else {
return [...acc, curr]
}
}, []);
or if type reccurs, copy only the name object..
this will return an array of same length but along the elements, type property will be removed if it recurrs...

Issue while using react-picky select menu

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"));

ng-selected true but not selecting

so, i have a select list and I am trying to select the item dynamically. The thing is, even doe the expression is evaluated to "true" the option is still not being selected
<label for="articlePage">Page:</label>
<select class="form-control pageList" name="articlePage" required="" ng-model="article.page_ID">
<option ng-repeat="page in pages" ng-selected ="{{page.id == article.page_ID}}" value={{page.id}}>{{page.name}}</option>
</select><br>
the scope(pages):
$scope.pages = [
{ name: "Home", id: "1" },
{ name: "Plugs", id: "2" },
{ name: "Pack Bedding", id: "3" },
{ name: "Pot Bedding", id: "4" },
{ name: "Poinsettias", id: "5" },
{ name: "Sales", id: "6" },
{ name: "Process Quality", id: "7" },
{ name: "Environment", id: "8" },
{ name: "Process Technology", id: "9" },
{ name: "Process Control", id: "10" },
{ name: "Infrastructure", id: "11" },
{ name: "News", id: "12" },
{ name: "About", id: "13" },
{ name: "Contact", id: "14" },
{ name: "Find Us", id: "15" },
{ name: "Key Personnel", id: "16" },
{ name: "Recruitment", id: "17" },
{ name: "Legal Information", id: "18" },
{ name: "Hidden", id: "19" }
];
there is also an service that is retrieving my articles, i know i get that right and like i said, the expression is being evaluated. here is a print screen to prove that:
does anyone have any idea why the option isn't being selected?
Thank you! :)
You don't need expression inside the ng-selected! Try this:
<label for="articlePage">Page:</label>
<select class="form-control pageList" name="articlePage" required="" ng-model="article.page_ID">
<option ng-repeat="page in pages" ng-selected ="page.id == article.page_ID" value="{{page.id}}">{{page.name}}</option>
</select><br>

Resources