How do I write a function that takes an array of components and instantiates them all in its enclosing scope?
const = [component1, component2,...]
// into
<Component1 />
<Component2 />
...
If you have your components with their props ready to use in the array you can use the array itself, cause it works the same as Fragment. If you need to pass props to your component you can map through the array and pass props.
const Todo = ({id, done, text}) => (
<li key={id}>
<label>
<input type="checkbox" disabled readOnly checked={done} />
<span className={done ? "done" : ""}>{text}</span>
</label>
</li>
)
const Todos = [
// Render with jsx
<Todo text="Learn React" done={false} id={2} />,
// Render with createElement
React.createElement(Todo, {text: "Learn JavaScript", done: false, id: 1}),
// Render with function call (not possible all the time e.g. some ref cases)
Todo({text: "Play around in JSFiddle", done: true , id: 3}),
]
const TodoApp = () => (
<ol>
{[Todos]}
</ol>
)
Of course, you can alter the array before committing to the screen
const FancyMapperComponent({size}) {
return (
<ul>
{Array.from({length:size}).map((_, i) => (
<li key={`unique-${i}`}>Text content {i}<li/>
)}
</ul>
)
}
const Example = (props) => {
const context = {};
const newProps = {
a: '1',
b: '2',
}
return (
<Context.Provider value={context}>
{[Component1, Component2].map((Component) => (
<Component {...newProps} />
))}
</Context.Provider>
);
};
[Component1, Component2].map(Component => <Component />)<div>{components}</div>.