Adding selected options to state array reactjs - arrays

I am working on an ecommerce application
I am using react-select to select multi category
I want to get the value selected by the use and add it to the state category
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const AddProductModal = ({addOpenProductModal, setAddOpenProductModal}) => {
const [category, setCategory] = useState({
category: []
})
const handleChange = (e) => {
// let {label, value} = e.target;
console.log(e);
// setCategory({ category: [...category, 'new value'] })
}
return (
<div>
<Select
onChange={handleChange}
isMulti
name="categories"
options={options} />
</div>
)
}
export default AddProductModal

Related

Can't save value into database through Reactjs Component

I just start learning Reactjs and I have trouble with Component. Here are my code:
export default function ChonLanguage() {
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;
}
return (
<Select className={`col-12 o-languages`}
onChange={handleChangeOption()}
options={options} />
)
}
It shown my options, but when I submit, I not save into Database. What should I change? Thanks
Made some minor changes to your code.
Kindly note:-
setSelectedOption is function of type React.dispatch<[]> which will update selectedOption state value so you need to pass some value in that.
useEffect is used to check the updated value of selectedOption, you may not use it.
export default function ChonLanguage() {
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 = (event) => {
return setSelectedOption(event.value);
};
useEffect(() => {
console.log(selectedOption);
}, [selectedOption]);
return (
<Select
className={`col-12 o-languages`}
onChange={(e) => {
handleChangeOption(e);
}}
options={options}
/>
);
}

I want to save just value in react-select

I have some trouble with my react-select: When I click 'Submit', it save an object that have both 'value' and 'label' like this:
enter image description here
All I need is when I choose, it's show label list, and when I submit, it save only value. What can I do? Here are my code:
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: 'vi', label: 'Vietnamese' },
{ value: 'en', label: 'English' },
{ value: 'zh', label: 'Chinese' },
{ value: 'ja', label: 'Japanese' },
{ value: 'de', label: 'German' },
];
//This is Select part
<Select
onChange={(e) =>setMainLang(e)}
options={mainLangOptions}
/>
You need to set the option value as the mainLangOptions.value and the label as
mainLangOptions.label. By doing that you will display the label as option labels and save the value as the value of option tag. Check out the code below :
import React from "react";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
mainLanguage: ""
};
}
onOptionChangeHandler = (event) => {
this.state.mainLanguage = event.target.value;
console.log(this.state.mainLanguage);
};
render() {
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<div>
<select onChange={this.onOptionChangeHandler}>
<option>Please choose one option</option>
{mainLangOptions.map((option, index) => {
return (
<option value={option.value} key={index}>
{option.label}
</option>
);
})}
</select>
</div>
);
}
}
export default App;
You must use e.target.value inside your setMainLang
<Select onChange={(e) => setMainLang(e.target.value)}>
This should work for your code but if it doesn't work, here is a complete code that I have tested in code sandbox and you can try it.
import React, { useState } from "react";
import { Select } from "#chakra-ui/react";
const Users = () => {
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<>
<Select onChange={(e) => setMainLang(e.target.value)}>
{mainLangOptions.map((op) => (
<option value={op.value}>{op.label}</option>
))}
</Select>
<h1>{mainLang}</h1>
</>
);
};
export default Users;

How to clear a select field when another select field changes with react-select

So I have 2 select fields. Then first select field is for categories; The other one is for subcategories. When the first field changes, the second field changes the list of options to choose, but the selected value of the second select field is still there. So I was wondering if there's a way to deselect the second value, when the first value changes.
Code:
import { useEffect, useState } from 'react';
// import categoryOptions from './categoryOptions';
import subcategoryOptions from './subcategoryOptions.json';
import Select from 'react-select';
const Info = ({
register,
errors,
product,
setValue,
getValues,
watchAllFields,
formStep,
unregister,
}) => {
const categories = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
const [selectedCategory, setSelectedCategory] = useState(null);
const [selectedSubcategory, setSelectedSubcategory] = useState(null);
const [subcategoryArray, setSubcategoryArray] = useState();
const [isChanged, setIsChanged] = useState(false);
useEffect(() => {
setSelectedSubcategory(null);
if (selectedCategory) {
const foundSubcategory = subcategories.filter(
(item) => item.category === selectedCategory.value
);
if (foundSubcategory) {
console.log(foundSubcategory);
setSubcategoryArray(foundSubcategory);
}
}
setIsChanged(true);
}, [selectedCategory]);
const subcategories = [
{ value: '', label: '⠀' },
{ value: 'eee', label: 'Chocolate', category: 'chocolate' },
{ value: 'e', label: 'zre', category: 'chocolate' },
{ value: 'es', label: 'Chooo', category: 'chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
return (
<section className='px-10'>
<div className='flex flex-col'>
<label htmlFor='title' className='pb-5 text-2xl text-white'>
Title
</label>
<input
type='text'
name='title'
className='text-white bg-indigo-900 border-indigo-900 input focus:bg-indigo-500'
placeholder='Try something creative (Required)'
maxLength={30}
{...register('title', {
required: {
value: true,
message: 'Title is required!',
},
})}
/>
{errors.title && (
<p className='mt-2 text-sm text-yellow-500'>{errors.title.message}</p>
)}
<h1 className='pt-10 pb-5 text-2xl text-white'>Gig Requierments</h1>
<textarea
type='text'
name='Requirements'
className='h-56 text-white bg-indigo-900 border-indigo-900 input focus:bg-indigo-500'
{...register('requirements')}
></textarea>
<h1 className='pt-10 pb-5 text-2xl text-white'>Category</h1>
<Select
defaultValue={selectedCategory}
onChange={setSelectedCategory}
options={categories}
/>
<Select
isClearable
defaultValue={selectedSubcategory}
onChange={setSelectedSubcategory}
options={subcategoryArray}
/>
</div>
</section>
);
};
export default Info;
Any help would be appreciated. Thanks.
Just pass a custom handler to the first Select that resets the second Select's value, if the currently selected subcategory is not in the new category:
const isSubcategory = (subcategory, category) => { /* returns true if subcategory is a subcategory of category */ }
const handleCategoryChange = useCallback(value => {
if (!isSubcategory(selectedSubcategory, value)) {
setSelectedSubcategory(null);
}
setSelectedCategory(value);
}, [selectedSubcategory])
<Select
isClearable
defaultValue={selectedCategory}
onChange={handleCategoryChange}
options={subcategoryArray}
/>
If the selected subcategory is never a subcategory of another category you can even skip the check.
The effect is not required. It all depends on local state changes.

How to implement AddAdiditions in React Sematic UI using Hooks?

I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox

How can i set only value on react select

I am using react-select with the isMulti attribute on a form. For simplicity the data are the following
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
if i select the first two options and then i submit the form, the react-select field will have the following value
reactSelectField: [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' }
]
how can i set the fieldValue to
reactSelectField: ['chocolate', 'strawberry']
which is actually the values of the options and not the whole object?
You could transform values yourself using onChange and a form state
const [values, setValues] = React.useState([]);
<Select
options={options}
value={values.map((value) => ({
label: value,
value,
})}
onChange={(values) => {
setValues(values.map((option) => option.value));
}}
/>
Or create your own wrapper to return the value in the format you expect
const MyMultiSelect = ({ values = [], options = [], onChange, ...props }) => (
<Select
{...props}
value={values.map((value) => ({
label: value,
value,
})}
options={options.map((value) => ({
label: value,
value,
})}
onChange={(values) => {
onChange(values.map((option) => option.value));
}}
/>
)
// Usage
<MyMultiSelect
options={["chocolate", "strawberry", "banana"]}
values={["chocolate", "banana"]}
onChange={(values) => {
console.log(values); // ["chocolate", "banana"]
}}
/>

Resources