Reputation: 723
I'm beginner in ReactJS and I'm with a problem with Selects. I have a Select
that renders some names with MenuItem
.
What I need is that Select
already comes with some names checked within the list of names. For example, the name Van Henry
and Ralph Hubbard
were already included in the list.
In order to know which item in the list should be marked, two arrays are compared, if the value in one is also in the other. So I mark that name in the list.
I'll show an image, I think I can explain better that way:
Here's my code I put at CodeSandBox: https://codesandbox.io/s/material-demo-4iksi?file=/index.js
Can someone help me? Thank you in advance.
Upvotes: 4
Views: 112
Reputation: 5288
You can use filter
to create a new array
from names
that are present on names2
. Then use useEffect
to set your personName
state.
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
React.useEffect(() => {
setPersonName(names.filter((name) => names2.includes(name)));
}, []);
Upvotes: 1
Reputation: 51
personName
is being checked to see if a value should be checked here:
<Checkbox checked={personName.indexOf(name) > -1} />
personName
is initialized as an empty array here: const [personName, setPersonName] = React.useState([]);
const [personName, setPersonName] = React.useState([...names2]);
would set all names in names2 array to be selected by default.
edit: edited after question was edited with more info
Upvotes: 0
Reputation: 1352
Update the value passed to renderValue
prop in <Select />
<Select
labelId="demo-mutiple-checkbox-label"
id="demo-mutiple-checkbox"
multiple
value={personName}
onChange={handleChange}
input={<Input />}
renderValue={(selected) => personName.join(", ")}
MenuProps={MenuProps}
>
Upvotes: 0