Reputation: 338
I'm new to React and I'm trying to make a Select
component that takes in an array as a prop and turns it into <option>
s.
Component:
import React, { Component } from "react";
class Select extends Component {
render() {
return (
<select>
{this.props.items.map((item) => (
<option>{item}</option>
))}
</select>
);
}
}
export default Select;
Render:
import React from "react";
import Select from './components/Select';
function App() {
return (
<div className="App">
<Select items={['Volvo', 'Subaru']} />
</div>
);
}
export default App;
I'm getting Cannot read property 'map' of undefined
.
Upvotes: 0
Views: 102
Reputation: 3333
For undefined error, You can use javascripts new ES2020 feature ?.
Also known as Optional Chaining
<select>
{this.props.items?.map((item) => (
<option>{item}</option>
))}
</select>
So this way if the items is undefined then you won't get an error
Upvotes: 1
Reputation: 1121
Select
component doesn't know that its props has an items
list in it, so you'll need to explicitly define it.
import React, { Component } from 'react';
interface SelectProps {
items: any;
}
class Select extends Component<SelectProps> {
render() {
return (
<select>
{this.props.items.map((item) => (
<option>{item}</option>
))}
</select>
);
}
}
export default Select;
Upvotes: 1