I have this select component with their values taken from the useEffect data. In this component, I could see in the console the value that was selected from the select
const SelectName = () => {
const [value, setValue] = useState(0);
const [names, setNames] = useState([]);
const handleChange = (e) => setValue(e.target.value);
useEffect(() => {
const unsubscribe = firestore
.collection("name")
.onSnapshot((snapshot) => {
const arr = [];
snapshot.forEach((doc) =>
arr.push({
...doc.data(),
id: doc.id,
})
);
setNames(arr);
});
return () => {
unsubscribe();
};
}, []);
// console.log(value);
return (
<div>
<FormControl fullWidth>
<InputLabel htmlFor="names">Names</InputLabel>
<Select onChange={handleChange} fullWidth>
{names &&
names.map((user) => (
<MenuItem
key={user.firstName + " " + user.lastName}
value={user.firstName + " " + user.lastName}
// defaultValue={}
>
{user.firstName + " " + user.lastName}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
};
export default SelectName;
And I have this other component with other fields, and I wanted to add the select component here. However, I cannot get the value of the selected component in this form. I would also be using the select component twice in this component; first with the 1st selected name and 2nd selected name. And there might be instances where the user might enter different names of the 1st and 2nd select.
I tried putting value and onChange on the first select component but I cannot see the selected value in the console. How would I be able to get the values from select? Thank you.
const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
console.log(value);
<form onSubmit={handleSubmit}>
//other fields
<Grid item>
//1st selected Name
<SelectName
value={value}
onChange={handleChange}
/>
</Grid>
<Grid item>
//2nd selected Name
<SelectName/>
</Grid>
<ButtonForm type="submit" fullWidth>
Submit
</ButtonForm>
</Grid>
</Grid>
</form>
You should destructure the passed value and onChange props and use these instead of the local value component state.
const SelectName = ({ value, onChange }) => {
const [names, setNames] = useState([]);
useEffect(() => {
const unsubscribe = firestore
.collection("name")
.onSnapshot((snapshot) => {
const arr = [];
snapshot.forEach((doc) =>
arr.push({
...doc.data(),
id: doc.id,
})
);
setNames(arr);
});
return () => {
unsubscribe();
};
}, []);
return (
<div>
<FormControl fullWidth>
<InputLabel htmlFor="names">Names</InputLabel>
<Select
value={value} // <-- pass value
onChange={onChange} // <-- pass change handler
fullWidth
>
{names &&
names.map((user) => (
<MenuItem
key={user.firstName + " " + user.lastName}
value={user.firstName + " " + user.lastName}
>
{user.firstName + " " + user.lastName}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
};
As an optimization, and to generalize further, you may want to factor out the firestore logic as well, into the parent and pass the options in as a prop.