M
M
Masterstvo2018-03-26 21:27:35
React
Masterstvo, 2018-03-26 21:27:35

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>

PS Redux do not offer))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2018-03-27
@Masterstvo

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>
    );
  }
}

M
Maxim, 2018-03-26
@maxfarseer

Use context as Redux or React-router does ( documentation )
Conext.API from 16 alpha - don't use it yet, not stable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question