I am trying to display the list of interests based on this object received from backend:
profile : {
interest: ["interest1", "interest2"],
};
This is how I implemented it:
import Creatable from "react-select/creatable";
class EditProfileInSettings extends Component {
constructor(props) {
super(props);
this.state = {
previously_selected_interests: [],
};
}
componentWillReceiveProps(nextProps) {
const { interest } = nextProps.profile;
if (!!interest) {
const previously_selected_interests = interest.map((interest) => ({
_id: interest._id,
value: interest.name,
label: interest.name,
color: "#FF8B00",
}));
this.setState({
previously_selected_interests,
});
}
}
render() {
let { previously_selected_interests } = this.state;
return (
<Creatable
cacheOptions
isMulti
defaultValue={previously_selected_interests}
/>
);
}
}
The problem is that even though inside render the previously_selected_interests
passed to defaultValue
are logged correctly:
~ file: EditProfileInSettings.js ~ line 64 ~ EditProfileInSettings ~ render ~ previously_selected_interests []
~ file: EditProfileInSettings.js ~ line 64 ~ EditProfileInSettings ~ render ~ previously_selected_interests (2) [{…}, {…}] 0: {_id: "609cd8253acf49906990d712", value: "mythology", label: "mythology", color: "#FF8B00"} 1: {_id: "609cd8253acf49906990d790", value: "listening to music", label: "listening to music", color: "#FF8B00"} length: 2 proto : Array(0)
But, when I set the exact same values statically inside render:
render() {
let { previously_selected_interests } = this.state;
previously_selected_interests = [
{
_id: "609cd8253acf49906990d712",
value: "interest1",
label: "interest1",
color: "#FF8B00",
},
{
_id: "609cd8253acf49906990d790",
value: "interest2",
label: "interest2",
color: "#FF8B00",
},
];
return (
<Creatable
cacheOptions
isMulti
defaultValue={previously_selected_interests}
/>
);
}
}
They do get displayed:
Which makes absolutely no sense, since they are the exact same array of the exact same objects.
So for some reason Creatable
component doesn't update defaultValue
.
Any idea how to fix this?
I have posted the issue on react-select Github Repo and I got my answer: the defaultValue
prop is is designed for "uncontrolled" behaviour of components. Using it will only change the value for the initial render of the component. You should Instead use the value
prop (in combination with the onChange
prop to handle changes):
<Creatable
cacheOptions
options={interests_options}
isMulti
value={previously_selected_interests_to_display}
onInputChange={this.handleInterestsInputChange}
onChange={this.onSelectedInterest}
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.