Answer the question
In order to leave comments, you need to log in
Is it possible to pass data to dynamically added components in react?
Hello!
Can you please tell me if it is possible to implement the following thing:
Usually props are used to pass data to a component: <Component data={data}>
Is it possible to pass data down the chain for dynamically added child components in React? Those. pass data only to the parent component and make it available to child components too?
For example:
<Parent data={data} />
[...ChildeComponents]
</Parent>
Answer the question
In order to leave comments, you need to log in
Possible without context:
import React, { Component, cloneElement } from 'react';
export default class Parent extends Component {
render() {
const { data, children } = this.props;
const childrensArray = React.Children.toArray(children);
return (
<div>
{childrensArray.map((children) => cloneElement(children, { data }))}
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question