I am creating ReactJS application in which i want to render the child objects from the parent object in dropdown using materialUI select. I tried to implement it by iteration over the object using map() function but i am not getting value when i click on the dropdown.
Here is my source code for creating dropdown.
import React from "react";
import { Select, MenuItem, FormControl, InputLabel } from "@material-ui/core";
import "./CamSelect.css"
export default class CamSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
currentLocation: localStorage.getItem("location"),
data: [
{
location: "abc",
link: [
{name: "cam1", url: "https://...."},
{name: "cam2", url: "https://...."}
]
},
{
location: "xyz",
link: [
{name: "cam1", url: "https://...."},
]
},
],
selected: '',
};
}
handleChange = (event) => {
this.setState({ selected: event.target.value, name: event.target.name });
};
renderOptions() {
return this.state.data.map((dt, i) => {
if(this.state.currentLocation == dt.location){
dt.link.map(lnk => {
console.log(lnk.name)
return (
<MenuItem
label="Select a camera"
value={lnk.url}
key={i}
name={lnk.name}
>
{lnk.name}
</MenuItem>
)
})
}
}
)
};
render() {
return (
<FormControl className="camera-select" style={{ minWidth: "100px"}}>
<InputLabel id="demo-simple-select-label" style={{color:"white"}}>Cam</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
className="camera-text-color"
value={this.state.selected}
onChange={this.handleChange}
>
{this.renderOptions()}
</Select>
</FormControl>
);
}
}
My Expectation is that when currentLocation will be equal to location key i.e "abc" which is in the array object then i want to display cam1, cam2 value in the dropdown.
When you are iterating over dt.link.map you do not return the result, so renderOptions also does not return anything => nothing is rendered.
You should have a return here:
return dt.link.map(lnk => {
This will return a JSX.Element[][], and you want a JSX.Element[]. If there will be only one matching location, you could do this.state.data.find(dt => this.state.currentLocation == dt.location).map(...)