I have 2 types of components, for example a <Promo /> and an <Announcement />
One of my components maps over a list of items and creates either promos or announcements, how can I pass an ItemElement, rather than have to repeat the mapping based on an if statement.
current implementation
import React, { Component } from 'react'
import Promo from './Promo'
import Announcement from './Announcement'
class Demo extends Component {
render() {
const { ItemElement } = this.props
let items = null
if(ItemElement === 'Promo'){
items = this.props.items.map((p, i) => (
<Promo item={p} />
))
} else if(ItemElement === 'Announcement') {
items = this.props.items.map((a, i) => (
<Announcement item={a} />
))
}
return (
{ items }
)
}
}
desired implementation not working
import React, { Component } from 'react'
import Promo from './Promo'
import Announcement from './Announcement'
class Demo extends Component {
render() {
// this would be 'Promo' or 'Announcement'
const { ItemElement } = this.props
let items = this.props.items.map((p, i) => (
<ItemElement item={p} />
))
return (
{ items }
)
}
}
This works fine if I pass in say a 'div' or 'a' or 'span' tag, but not for my own components?
render()method doesn't actually return anything. You should probably have areturn (<div>{this.props.items.map(...)}</div>);in there