V
V
valerav2018-09-30 16:37:31
React
valerav, 2018-09-30 16:37:31

How to recursively traverse all child components in react?

While doing server-side rendering of react, there was a problem fetching data on the server. There is a router configuration file:

const routes = [
{
    path: '/',
    exact: true,
    component: HomePage
},
{
    path: '/news',
    component: NewsPage
},
{
    path: '/contacts',
    component: ContactsPage
},
{
    path: '*',
    component: NotFoundPage
}
];

On the server, using the matchRoutes function from the react-router-config library, I get the necessary component from the routes array based on the URL and “pull” the static fetchData method, which dispatches the necessary actions.
Question: With this approach, you need to declare the fetchData function on the topmost component, but what if I have several nested components that also load data from outside, what should I do in this situation? The first thing that comes to mind is to add an array with components that fetch data to the configuration file, but at the same time you need to constantly synchronize the config ... I would like to go through the entire tree of nested components and call fetchData. Is it possible? Or is there another approach to ssr that solves this problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question