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>
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 .
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With