Feeding the react-select component the selected state to the value prop, makes it unable to select anything at all? I'm trying to feed the value-prop with the selected state so that i can reset react-select via setState. What am i doing wrong here?
Select Component with isMulti option:
import SelectForm from "react-select";
const Select = (props) => {
const options = props.options.map((option) => ({
value: option,
label: option.toLowerCase(),
}));
const costumStyles = {
container: (baseStyles) => ({ ...baseStyles, width: "100%" }),
control: (baseStyles) => ({
...baseStyles,
backgroundColor: "transparent",
borderStyle: "none",
borderRadius: "15px",
marginTop: "3px",
}),
singleValue: (baseStyles) => ({ ...baseStyles, color: "white" }),
};
const handleChange = (event) => {
props.onChangeOption(event);
};
return (
<div>
{props.isMulti ? (
<SelectForm
options={options}
onChange={handleChange}
styles={costumStyles}
placeholder={props.placeholder}
value={props.value}
isMulti
/>
) : (
<SelectForm
options={options}
onChange={handleChange}
styles={costumStyles}
placeholder={props.placeholder}
value={props.value}
/>
)}
</div>
);
};
export default Select;
The parent component which uses the Select component:
import React, { useState } from "react";
import Select from "../../input/Select";
const CreateJobPage3 = (props) => {
const [department, setDepartment] = useState();
const [subDepartment, setSubDepartment] = useState([]);
const departments = [jobDepartment1, jobDepartment2, jobDepartment3];
const subDepartments = [jobSubDepartment1, jobSubDepartment2, jobSubDepartment3];
const departmentHandler = (props) => {
setDepartment(props.value);
setSubDepartment([]);
};
const subDepartmentHandler = (props) => {
setSubDepartment(props.map((item) => item.value));
};
return (
<>
<Select
placeholder="Choose Department"
options={departments}
onChangeOption={departmentHandler}
value={department || ""}
/>
<Select
placeholder="Choose Sub-Departments"
options={subDepartments}
onChangeOption={subDepartmentHandler}
isMulti={true}
value={subDepartment || ""}
/>
</>
);
};
export default CreateJobPage3;
CodePudding user response:
According to the docs of react-select
they're expecting complete option to be passed in value array.
Say for example, we have options like
const options=[
{ value: 'blue', label: 'Blue', color: '#0052CC', isDisabled: true },
{ value: 'red', label: 'Red', color: '#0052CC', isDisabled: true }
];
then we have to pass value as,
value={[{ value: 'blue', label: 'Blue', color: '#0052CC', isDisabled: true }]}
Refer this example: https://codesandbox.io/s/17g0yy?module=/example.tsx
Try this,
const departmentHandler = (props) => {
setDepartment(props);
setSubDepartment([]);
};
const subDepartmentHandler = (props) => {
setSubDepartment(props);
};