7

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>

3 Answers 3

11

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).

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.