Solo
Solo

Reputation: 6957

Pass something to render function

Current routes:

// React render() return example
<Switch>
  <Route path="/" exact render={this.renderPage}/>
  <Route path="/search" render={this.renderPage}/>
  <Route path="/profile" render={this.renderPage}/>
  <Route render={this.renderPage}/>
</Switch>

// here's the simplified method that Route-s call if path matches
renderPage(props) {
  // JS logic is here

  return [
    <ItemHeader key="header"/>,
    <ItemWrapper key="wrapper">
      {/* this is what the question is about: */}
      {/* how do I pass this dynamic Component here or even hint about it? */}
      <Component someProp={varBasedOnJSLogicAbove}/>
    </Wrapper>
  ];
}

How to pass any data to renderPage method?

I need to pass my component as variable (or any hint really - string etc) to renderPage method because I need to tell it what component I want it to render.

Why do you even need renderPage method?

There's JavaScript logic and I also need to wrap my Component with other components.


1. Why don't you use component prop on Route?

<Route path="/profile" component={Profile}/>

Because I need to wrap the component and inject some data into it, like in renderPage method.


2. Why don't you create a separate React component and do all the renderPage logic and wraping in it? You could pass everything you need as props, etc:

<CustomRoute path="/profile" component={Profile} anyThing="ILikeToPass"/>

Tried it, unfortunately it breaks Switch (I really need it), Route has to be direct child.


3. Why don't you use different method for every route? E.g renderProfile.

20 methods and each has exactly the same code except different Component? No thanks!


4. Why don't you just pass the data as function/method arguments?

<Route path="/profile" render={this.renderPage(Component, 'foo')}/>
// or
<Route path="/profile" render={() => this.renderPage(Component, 'bar')}/>

Doesn't work as needed. First option seems to overwrite the props (I need those) that React Router passes to my method and if you use arrow function - it passes only props, not my args.

5. Why don't you use pathname and figure it out yourself?

Use a single Route without path prop and do all the pathname parsing and logic in my method? That's a big if not the point of using a router and Route-s.. I don't want to rebuild the router.

Upvotes: 3

Views: 1404

Answers (1)

Kamil Socha
Kamil Socha

Reputation: 299

So, this is an answer:

Why not try:

<Route path="/profile" render={(props) => this.renderPage(props, Component, 'bar')}/>

Upvotes: 1

Related Questions