I have a simple list where I'm displaying a looped Select
using .map
.
Everything is working fine, but the initial default value of each select
is not what I have in my array list.
How do I set a defaultValue
for each select in the list?
https://codesandbox.io/s/festive-robinson-847oj?file=/src/App.js:0-1435
import React, { useState } from "react";
import Select from "react-select";
function SelectItem(props) {
const [value, setValue] = React.useState(props.list[0]);
return (
<Select
options={props.list}
onChange={(newValue) => {
setValue(newValue);
props.onChange(newValue.value);
}}
value={value}
/>
);
}
export default () => {
const animationsList = [
{ value: "animation1", label: "Dance" },
{ value: "animation2", label: "Flip" },
{ value: "animation3", label: "Salsa" }
];
const reactList = [
{
id: "1",
animation: "animation1"
},
{
id: "2",
animation: "animation2"
},
{
id: "3",
animation: "animation3"
}
];
const [links, setLinks] = useState(reactList);
const onChange = (index, animation) => {
const cloneLinks = [...links];
cloneLinks[index].animation = animation;
setLinks(cloneLinks);
console.log(cloneLinks);
};
return (
<div>
<ul>
<div>
{links.map((url, indexurl) => (
<li key={url.id}>
<div>
<SelectItem
onChange={(animation) => onChange(indexurl, animation)}
list={animationsList}
defaultValue={url.animation.value}
/>
</div>
</li>
))}
</div>
</ul>
</div>
);
};
A new state in the SelectItem
component is not needed.
The value
or defaultValue
must be an object from the list that is used for options.
Here's the updated CSB .
function SelectItem(props) {
return (
<Select
options={props.list}
onChange={(newValue) => {
props.onChange(newValue.value);
}}
value={props.value}
/>
);
}
export default () => {
const animationsList = [
{ value: "animation1", label: "Dance" },
{ value: "animation2", label: "Flip" },
{ value: "animation3", label: "Salsa" }
];
const reactList = [
{
id: "1",
animation: "animation1"
},
{
id: "2",
animation: "animation2"
},
{
id: "3",
animation: "animation3"
}
];
const [links, setLinks] = useState(reactList);
const onChange = (index, animation) => {
const cloneLinks = [...links];
cloneLinks[index].animation = animation;
setLinks(cloneLinks);
console.log(cloneLinks);
};
return (
<div>
<ul>
<div>
{links.map((url, indexurl) => (
<li key={url.id}>
<div>
<SelectItem
onChange={(animation) => onChange(indexurl, animation)}
list={animationsList}
value={animationsList.find(
(aL) => aL.value === url.animation
)}
/>
</div>
</li>
))}
</div>
</ul>
</div>
);
};
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.