I have array of cities with objects like this:
[{id: 1, name: 'New York'}, {id: 2, name: 'London'} ...]
and I have a value of id.
I put elements (names) from array to select list. But I need to add first option with value from array (name) which have the corresponding id which I can't make it work.
My component:
const propTypes = {
cities: PropTypes.array,
enteredEvent: PropTypes.array
};
class newEvent extends Component {
constructor(props) {
super(props);
this.state = {
showInOption: ''
};
this.handleDictionary = this.handleDictionary.bind(this);
this.searchTypeEvent = this.searchTypeEvent.bind(this);
}
componentDidMount() {
this.searchTypeEvent();
}
handleDictionary(e) {
...
}
searchTypeEvent() {
if (this.props.enteredEvent.cityid !== null && this.props.enteredEvent.cityid !== undefined) { // if I have id value
const type = this.props.cities.find(el => el.id === this.props.enteredEvent.cityid); // find an object with id
this.setState({ showInOption: type.name });
}
this.setState({ showInOption: 'Select something' });
}
render() {
return (
<div>
<select onChange={this.handleDictionary}>
<option>{this.state.showInOption}</option> // here I need to add a value
{this.props.cities.map(item => { // here I call other options
return (<InputSelect key={item.id} directory={item}/>);
})}
</select>
</div>
);
}
}
I have an error:
Uncaught TypeError: Cannot read property 'name' of undefined
How can I fix it?
It seems you need filter.It will return an array of object
let a = [{
id: 1,
name: 'New York'
}, {
id: 2,
name: 'London'
}]
function b(idToSearch) {
return a.filter(item => {
return item.id === idToSearch
})
};
console.log(b(1))
Try this
const type = Array.isArray(this.props.cities) && this.props.cities.find(el => el.id ==this.props.enteredEvent.cityid);
this.setState({ showInOption: type ? type.name : null });
Make sure the name you enter matches with any one of the object in array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With