ctrlplusb / react-async-component

Resolve components asynchronously, with support for code splitting and advanced server side rendering use cases.
MIT License
1.45k stars 62 forks source link

Is it possible to send props to the resolved component ? #31

Closed thomasthiebaud closed 7 years ago

thomasthiebaud commented 7 years ago

I am using react-router v4 and I have this code

import React from 'react'
import Route from 'react-router-dom/Route'

import LazilyLoad from './LazilyLoad'

const Async = route => (
  <Route
    path={route.path}
    render={props => (
      <LazilyLoad render={route.component} >
        {Component => (
          <Component {...props} routes={route.routes} />
        )}
      </LazilyLoad>
    )}
  />
)

Where LazilyLoad is my own async component. I would like to switch to react-async-component since your code is way better, but I cannot manage to send props to the resolved component.

Right now I have this code (where route.component return System.import(...))

const Async = route => (
  <Route
    path={route.path}
    component={
      asyncComponent({
        resolve: () => route.component,
      })
    }
  />
)

But I get

Warning: Failed prop type: The prop routes is marked as required in DashBoard, but its value is undefined.

since I not longer have routes={route.routes}

So, is it possible to send props to a resolved component ? If yes, how ? If no, is it desired feature that maybe I can try to implement and PR ?

ctrlplusb commented 7 years ago

Hey @thomasthiebaud!

Yeah, you should be able to do this.

I am not 100% about what you are trying to achieve and what your constraints are, but below is a simple example where I have a route object definition (that could refer to a normal or async component), and a generic higher order function to produce routes that accept props.

const homeRoute =  { 
  Component: AsyncHomeRoute,  // created with asyncComponent
  path: '/', 
  exact: true 
}

// A higher order function that accepts a "route" object and produces
// a Route component that accepts props
const routeWithProps = route => props => {
  const { Component, exact, path } = route
  return (
    <Route
      path={path}
      exact={exact}
      render={routerProps => <Component {...routerProps} {...props} />}
    />
  )
}

const HomeRouteWithProps = routeWithProps(homeRoute)

<HomeRouteWithProps foo="bar" />

Hope this helps.

thomasthiebaud commented 7 years ago

Thanks a lot, shame on me for not finding it

ctrlplusb commented 7 years ago

Ain't no shame in programming. Sometimes we just need a different perspective. 😊