why is react select default value not working - reactjs

I am trying to use react select and trying to set a defaultValue but when I set a default value it does not appear on my dropdown. I have tried everything and then came here for help. any help would be appreciated. below attached is the code :
<Select
classNamePrefix="react-select"
options={
countryDetails
? countryDetails.map((c) => ({
label: c.label.split("-")[0],
value: c.value
}))
: [{ label: "", value: "" }]
}
name="operatingCountry"
placeholder={t("Select Country")}
components={{ ValueContainer: CustomValueContainer }}
defaultValue={
(console.log(
"country boy",
countryDetails.find((c) => c.value == defaultCountryUser)
),
countryDetails.find((c) => c.value == defaultCountryUser))
}
value={this.props.basicInfo["operatingCountry"].value}
onChange={({ label, value }) => {
this.props.selectChanged(
"operatingCountry",
{ label, value },
sectionKey
);
}}
/>
the console in the defaultValue gives result in console. as an object {label:"two",value:2}

The value should be an object. Try changing value to this:
value={this.props.basicInfo["operatingCountry"]}

Related

material ui always return 0 onchange

when i try to change the value in autocomplete of material-ui, i always get its value 0, here i have uploaded my whole code, can anyone please check my code and help me to resolve this issue ?
any help will be really appreciated.
export default function CreatePIC() {
const classes = useStyles();
const Department_list = [
{ label: 'Department1', id: 1 },
{ label: 'Department2', id: 2 },
{ label: 'Department3', id: 3 },
{ label: 'Department4', id: 4},
{ label: 'Department5', id: 5 }
]
const [department, setDepartment] = React.useState('');
const handleChangeDepartment = (event) => {
console.log(event.target.value);
setDepartment(event.target.value);
};
return (
<Autocomplete
id="Department"
value={department}
helperText={error.department}
options={Department_list}
getOptionLabel={option => typeof option === 'string' ? option : option.label}
onChange = {handleChangeDepartment}
renderInput={(params) => <TextField {...params} label="Search Department" variant="outlined" placeholder="Add Department" />}
/>
)
}
Ciao, in Autocomplete component event.target.value will be always 0. If you want to get the selected department you could use value in handleChangeDepartment. So your code becomes:
const handleChangeDepartment = (event, values) => {
console.log(event.target.value); // print always 0
console.log(values); // print values selected like { label: 'Department1', id: 1 }
setDepartment(values.label); // set department with values.label
};
Here a codesandbox example.
Rather than using:
event.target.value
try using:
event.target.innerText
or, to find the option index, use:
event.target.dataset.optionIndex

React select set value in select

As I understood, in react-select (latest) you need to send an object to the value props, to select/preselect an option. I am also using react-hook-form for my form management.
Is it possible to set the value through react-select or do I need to use react-hook-form's setValue()
As I click on an Item, I send this to my states:
const handleSectionOnClick = (id) => {
setTravelRoute({
'LocationEnd': { value: +travelRoutes[id].LocationIdEnd, label: travelRoutes[id].LocationCityEnd },
'LocationStart': { value: +travelRoutes[id].LocationIdStart, label: travelRoutes[id].LocationCityStart },
'startDate': new Date(),
'endDate': new Date()
})
}
My Demo object looks like this:
{
'LocationCityEnd': "Berlin, Ger",
'LocationCityStart': "Hattingen, Ger",
'LocationIdEnd': 2,
'LocationIdStart': 1,
'startDate': new Date(),
'endDate': new Date()
}
My (LocationStart) select component looks like this:
<Controller
render={({ onChange }) => (
<Select
styles={customStyles}
onChange={handleOnChangeStartLocation}
name="startLocation"
value={travelRoute?.LocationStart}
options={selectOptions}
placeholder="Choose..."
/>
)}
name="startLocation"
className={`${errors.startLocation ? 'inputSelectError' : ''}`}
control={control}
rules={{ required: true }}
/>
Nothing gets selected, not even the value/label.
What Am I missing? Thank you!
EDIT:
I added the handleOnChangeStartLocation function:
const handleOnChangeStartLocation = e => {
const { value, label } = e;
setTravelRoute(prevState => ({
...prevState,
LocationIdStart: value,
LocationCityStart: label
}))
}
The problem seems to be that you are not updating LocationStart with the new value/label. You should do something like:
const handleOnChangeStartLocation = e => {
const { value, label } = e;
setTravelRoute(prevState => ({
...prevState,
LocationStart: e, // add this line of code
LocationIdStart: value,
LocationCityStart: label
}))
}

react-select change name of option fields from ({ value: '', label:''}) to ({ id: '', name:''})

Is there a way to change the fields of an option object?
From my BE API i get:
const items = [{ id: 1, name:'dropdown1'}, { id: 2, name:'dropdown2'}];
So now i have to remap the fields to value and label, it would have been nice if i could set those fields dynamically, maybe something like:
<Select
optionRemapping={{value: 'id', label: 'name'}}
options={items}
/>
Or maybe i have missed a pattern on how people do this?
Doing the below feels a bit wrong.
items.map((item) => {
return { value: item.id, label: item.name };
});
Use getOptionLabel and getOptionValue props.
<Select
getOptionLabel={option => option.name}
getOptionValue={option => option.id}
options={items}
/>
example : https://codesandbox.io/s/kmoyw8q667
You could achieve your mapping by doing the following and deconstructing your items :
<Select
options={items.map(({ id, name }) => ({ value: id, label: name}))}
/>

I can't hanbleChange with react-select

I want to change it by using contact-select, but I keep getting an error.
When I select this option, I can see this error. help me plz.
error
this is options
const options = [
{ value: 'descript', label: '주관식' },
{ value: 'choice', label: '객관식' },
{ value: 'combine', label: '다중식' }
];
and this is onChange fuction
onChangeTmpType = (e) => {
this.setState({
tmp_type: e.target.value
})
}
this is React-Select
<Select
components={makeAnimated()}
value={this.state.tmp_type}
onChange={this.onChangeTmpType}
options={options}
/>
As specified in the documentation here, the onChange function looks like this:
function (
One of <
Object,
Array<Object>,
null,
undefined
>,
{
action required One of <
"select-option",
"deselect-option",
"remove-value",
"pop-value",
"set-value",
"clear",
"create-option"
>
}
) => undefined
and the e const you declare actually has the following structure:
{
label: ...,
value: ...
}
so no target key here but directly e.value if what you want is to access the props value.
Here a live example with console.log so you can see what's happening.
Replace your onChangeTmpType function as follows.
onChangeTmpType = (e) => {
this.setState({
tmp_type: e.value
})
}
The reason for this as (#Laura mentioned before) is that the e from react select only contains the value and the label .

React | Single onchange method for multiple dynamic select box

I'm getting response from API like below json. By using that response I'm generating dynamic select.
Issue:
Not able to select different value for different selectbox. I'm trying to achieve with state. How to declare state dynamically in this case.
JSON
const jsonFields = {
fields: [
{ name: "sex", value: ["m", "f"] },
{ name: "age", value: ["10", "20"] }
]
};
note: I don't know json key name like sex and age. name will be dynamic
Select Change:
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
Loading fields:
loadfields = () => {
const FieldsArray = [];
let FieldsData = jsonFields.fields;
FieldsData.forEach((val, index) => {
let FieldsDatavalue = val.value;
FieldsArray.push(
<FormControl>
<InputLabel htmlFor="controlled-open-select">{val.name}</InputLabel>
<Select
value=""
onChange={this.handleChange}
inputProps={{
name: "age"
}}
>
{FieldsDatavalue.map(option => (
<MenuItem key={option} value={option}>
{option}
</MenuItem>
))}
</Select>
</FormControl>
);
});
return FieldsArray;
};
Scenario : Code Sandbox
You're not storing the selected value in your state, and the name in inputProps is hard coded to 'age'. If you fix those problems, it works:
<Select
value={this.state[val.name] ? this.state[val.name] : ''}
onChange={this.handleChange}
inputProps={{name: val.name}}
>
Here's a CodeSandbox link.
UPDATE: The undefined values cause the label to overlap with the selected value, and since you retrieve them dynamically and cannot initialize them in the state, you can use a conditional this.state[val.name] ? this.state[val.name] : '' to fix the labels. (sandbox has been updated)

Resources