1

I am using react router v4 and react v16. There is a need where some components be mounted only once (when rendered first time), but rendered based on the Router path matches. (One such use case is to show a report for a menu item click, and at a later invocation, the report shown need not be fetched again).

Using Switch or just plain Route component -- the component gets unmounted, when that component is not in the path.

Currently, I am doing like this (which solves the issue in hand):

<main>
  <Route exact path="/" component={Home} />
  <WrapRoute exact path="/about" component={About} />
</main>

const WrapRoute = ({path, ...rest}) => (
  <div style={{display: rest.location.pathname == path ? "block" : "none"}}>
    <Route {...rest} />
  </div>
)

But I don't think directly verifying the location.pathname is a good idea. I would like 'Route' component to handle this.

I would like suggestions in handling this scenario (in such a way that the component is not re-mounted again). A solution or a different pattern, to address this is welcome.

1 Answer 1

3

While I am not sure, if there is a better pattern, that can solve this -- the following code is better than what is provided.

Update:

Though one could call matchPath function, I just realized that calling "children" parameter is a better option.

  <Route exact path="/dc/:id" children={({ match, ...rest }) => (
    <div style={{display: match && match.params.id === id.toString()
      ? "block"
      : "none"
    }}>
      <Component {...rest} match={match} />
    </div>
  )} />

Earlier solution:

matchPath function from react-router can do exactly identify -- whether this path will get matched or not.

<main>
  <Route exact path="/" component={Home} />
  <WrapRoute exact path="/about" component={About} />
</main>

......

import { matchPath } from 'react-router'

const WrapRoute = ({path, exact, ...rest}) => (
  <div style={{display: matchPath(rest.location.pathname, { path, exact })
    ? "block"
    : "none"
  }}>
    <Route {...rest} />
  </div>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.