6

I have array with thee values:

let elements = ["div", "span", "button"] 

How can I dynamically generate these elements in DOM using forEach or map iterator in ReactJS?

So as output I want to have:

<div> Value1 <div>
<span> Value 2 </span>
<button> Click me! </button>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Stepan Kovalyshyn
  • 186
  • 1
  • 2
  • 12

3 Answers3

9

Use createElement directly, rather than writing JSX (which does that under the hood):

const Test = (props) => {
    let elements = ["div", "span", "button"];
    return (
        <div>
            {
                elements.map((el, index) => 
                    React.createElement(el, { key: index }, "hello"))
            }
        </div>
    );
};

ReactDOM.render(<Test />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

From the docs:

React.createElement(type, [props], [...children])

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), or a React component type (a class or a function).

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
3

If you really want to do that, it's as simple as

React.createElement('div', {attribute: 'value'}, [children])

Just replace 'div' with your variable. Docs

mpen
  • 272,448
  • 266
  • 850
  • 1,236
0

I have found Gaurav Singhal sharing great example in terms of how to use React.createElement:

let WelcomeText = React.createElement(
  "h1",
  { style: { color: "blue" } },
  "This is a welcome text"
);

This will lead you to have

<h1 style="color:blue">
  This is a welcome text
</h1>

but if you are just beginner or slow learner like me, and somehow you just need more reference to know whether there is alternative way, I have found Corentin de Boisset and array.map() both introducing how to use array.map() in JSX, I myself also use array.map() to play video in JSX and it works:

    constructor (props) {
      super (props);
      this.state = {playList = []}
    }

    render() {
        let dynamicPlayer = this.state.playList.map((items) => {
            return (
                <ReactPlayer
                url= {items.source}//'storage/star_war.mp4'
                className='react-player'
                width='100%'
                height='100%'
                volume={items.volume}
                controls = {true}
                />)
        })

        return (
            <Container>
                <div>{dynamicPlayer}</div>
            </Container>
        );
    }

Though I would recommend React.createElement as well.

Conrad
  • 23
  • 4