Cecilia Chan Cecilia Chan - 1 year ago 71
React JSX Question

Custom component failed with map

I try to write to make my own custom component but it doesn't work as I wish. The interaction seems ok but the it's only render the last item of the arrays.

export default class MyComponent extends Component {

constructor() {

this.state = {
openItems: false,
selectedItem: 'Please select'

render() {

const { items, className } = this.props
const { openItems, selectedItem } = this.state

return (
<div className={classnames('myComponent', className)}>
<div tabIndex="1"
onBlur={() => this.setState({ openItems: false })}
onFocus={() => this.setState({ openItems: true })}>

<div className={classnames({'show': openItems === true, 'hide': openItems === false})}>
{items.map((obj, i) => {
<li onClick={() => this.setState({ selectedItem: obj.name, openItems: false })}

and somewhere I used the component like this

<MyComponent items={[{
name: 'abc',
name: 'def',
name: 123
}]} />

I have no clue what the mistake is.

Answer Source

Your component expects an array of object with the key name. When you've initialized your component, you've only passed in a single object with the key name duplicated three times:

<MyComponent items={[{
  name: 'abc',
  name: 'def', // <-- this overrides the previous 'abc'
  name: 123 // <-- this overrides the previous 'def'
}]} />

What you want is this:

<MyComponent items={[
  { name: 'abc' },
  { name: 'def' },
  { name: 123 },
]} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download