How can I dynamically create a component based on a prop or variable using React.createElement

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?

Answers:

Answer

Your render() method needs to return a single element. Right now you're returning a javascript object with a single property: items. You need to contain those items in a top level element, either another Component, or a DOM element (<div> or <span> or the like).

As for passing a component in as a prop, there's no reason you shouldn't be able to do that:

class Demo extends React.Component {

  render() {
    // this would be 'Promo' or 'Announcement'
    const { ItemElement } = this.props 

    let items = this.props.items.map((p, i) => (
      <ItemElement item={p} />
    ))

    return <ul>{items}</ul>;
  }
}

class Promo extends React.Component {
  render() {
    return <li>Promo - {this.props.item}</li>; 
  }
}

class Announcement extends React.Component {
  render() {
    return <li>Announcement - {this.props.item}</li>;
  }
}

const items = [
  "foo",
  "bar"
];

ReactDOM.render(
  <Demo 
    ItemElement={Promo} // <- try changing this to {Announcement}
    items={items} 
  />,
  document.getElementById('app')
);

Here's a jsbin demonstrating: http://jsbin.com/cakumex/edit?html,js,console,output

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.