How can i set only value on react select - reactjs

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"]
}}
/>

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;

MUI Textfield does not update State

I have an app which used various inputs which is functioning. For example, I have an initial dataset which is built from an API request, see below:
const [userData, setuserData] = useState([])
const companyuser = useSelector(state=>state.companyuser.currentUser)
useEffect(()=> {
const getUserData = async ()=>{
try{
const companyResponse = await userRequest.get(`companyprofile/findCompany/${companyuser._id}`);
setuserData(companyResponse.data.others)
}catch(err){}
};
getUserData()
},[])
const userInputDataSchema = [
{
id: 1,
label: "companyTitle",
type: "companyTitle",
placeholder: userData.companyTitle,
},
{
id: 2,
label: "surname",
type: "surname",
placeholder: userData.surname
},
{
id: 3,
label: "Email",
type: "email",
placeholder: userData.email
},
{
id: 4,
label: "Position",
type: "position",
placeholder: userData.position
},
{
id: 5,
label: "User Image",
type: "image",
placeholder: userData.userImage
},
{
id: 6,
label: "Professional Bio",
type: "professionalBio",
placeholder: userData.employees
},
{
id: 7,
label: "locationCity",
type: "locationCity",
placeholder: userData.locationCity
},
{
id: 8,
label: "locationCountry",
type: "locationCountry",
placeholder: userData.locationCountry
},
{
id: 9,
label: "whyWork_1",
type: "whyWork_1",
placeholder: userData.whyWork_1
},
];
This data is then mapped across the app, and will update when used. For example:
<UpdateUserDetailsSingular>
{userInputDataSchema.map((input) => (
<FormInput className="formInput" key={input.companyTitle}>
{input.id == 1 ?
<UserInput type={input.type} name="companyTitle" placeholder={input.placeholder}
onChange={handleChange} />
: null}
</FormInput>
))}
</UpdateUserDetailsSingular>
This is functioning. When I use the MUI larger input textfield, it does not update my state. It will dispaly the placeholder text, but if you type it will not handle it.
What is the reason?
{userInputDataSchema.map((input) => (
<div>
{input.id == 9 ?
<TextField
name="whyWork_1"
label="Diversity & Inclusion at Australia Post"
multiline
rows={15}
defaultValue={input.placeholder}
key={input.placeholder}
fullWidth
fullHeight
type={input.type}
handleChange={handleChange}
/> : null}
</div>
))}
</InputBoxContainer>
Does
The reason for this is could be a Mui related misconfiguration in TextField.
defaultValue any The default value. Use when the component is not controlled.
value any The value of the input element, required for a controlled component.
switching from defaultValue to value should do the job.

Adding selected options to state array reactjs

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

How to customize only one option from react-select?

I'm working with react-select and I want to customize only one option from the drop-down. Is there such an opportunity? I would like to do something like:
const CustomOption = ({ innerRef, innerProps, data }) => data.custom
? (<div ref={innerRef} {...innerProps} >I'm a custom link</div>)
: defaultOne //<--- here I would like to keep default option
<ReactSelect
components={{ Option: CustomOption }}
options={[
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
{ custom: true },
]}
/>
Any thoughts how to achive that?
Your feeling is good, you can achieve your goal with the following way:
const CustomOption = props => {
const { data, innerRef, innerProps } = props;
return data.custom ? (
<div ref={innerRef} {...innerProps}>
I'm a custom link
</div>
) : (
<components.Option {...props} />
);
};
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" },
{ custom: true }
];
function App() {
return <Select components={{ Option: CustomOption }} options={options} />;
}
The important thing to notice is to pass the entire props property to the components.Option to have the default behaviour.
Here a live example.

Resources