Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically generate DOM elements using ReactJS?

Tags:

reactjs

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>
like image 903
Stepan Kovalyshyn Avatar asked Nov 15 '17 17:11

Stepan Kovalyshyn


People also ask

Which function is used to create DOM elements with React?

When the ref attribute is used on an HTML element, the ref created in the constructor with React. createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current .

Can we do DOM manipulation in React?

Integrating with DOM Manipulation Plugins. React is unaware of changes made to the DOM outside of React. It determines updates based on its own internal representation, and if the same DOM nodes are manipulated by another library, React gets confused and has no way to recover.


2 Answers

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

like image 62
Tom Fenech Avatar answered Sep 20 '22 21:09

Tom Fenech


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

like image 27
mpen Avatar answered Sep 17 '22 21:09

mpen