With React-Router, How do I update the URL without triggering a re-render?

Viewed 2729

I have a parent component that should render another component when the URL is matches a certain path:

const View: React.SFC<Props> = ({
 ....
}) => {
  return (
    <div>
        ....
      <Route path={jobPath} component={JobPanel} />} />
    </div>
  );
};

JobPanel.tsx will render if jobPath === /careers/:id which all works.

JobPanel.tsx has a link that will currently go back with this.props.history.push(/careers)

<BackLink
  to="/company/careers"
  onClick={(e: any) => { handleClose(); }}
>
  <StyledChevron orientation={Orientation.Left} />
  Go Back
</BackLink>

or

<BackLink
  onClick={(e: any) => { this.props.history.push('/careers/); handleClose(); }}
>
  <StyledChevron orientation={Orientation.Left} />
  Go Back
</BackLink>

The problem is that JobPanel is supposed to have a transition in and out of the page with this Component:

class JobPanel extends Component {

render() {
  const { isOpen, handleClose, job } = this.props;
      return (
        <StyledFlyout
          active={isOpen}

Where isOpen is a boolean value in redux store.

While rendering JobPanel all works, I believe react-router is causing the page to re-render whenever the URL is changed. I'm not entirely sure on how to achieve no re-rendering.

1 Answers

Use the render prop instead of component in the Route. eg:

<Route path={jobPath} render={({ history }) => (
    <JobPanel {...routeProps} />
)} />

From https://reacttraining.com/react-router/web/api/Route/component:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

For more details on using render see https://reacttraining.com/react-router/web/api/Route/render-func for more details.

Related