Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router v4 unmounting when using render

Potentially a bit confused with how the render method works in react-router and what 'mounting' really means in React. I read the docs and it said that:

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 attribute, 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).

render: func This allows for convenient inline rendering and wrapping without the undesired remounting explained above.

So I expected that when the url changes, the existing component will be not be unmounted but instead stay there and hence save its state. But this is not what I observe. Here is my code:

<div style={styles.content}>
    <Route path={`${this.props.match.url}/summary`} render={() => <ETFViewer/>} />
    <Route path={`${this.props.match.url}/proxy`} render={() => <Proxy/>} />
</div>

So the components ETFViewer and Proxy get rendered fine and there's nothing wrong with them, but I notice that as I move from /proxy to /summary and back that the state is lost! Moreover, I can see in React devtools in Chrome that the component is indeed gone...

enter image description here

So what is going on here? Is there any way to allow the component to save its state and just "hide"?

Thanks for your help!

like image 218
coolboyjules Avatar asked Jun 15 '17 18:06

coolboyjules


1 Answers

This question is a bit old but came up in a recent search of mine. I believe the issue is that you are not passing down your props along with the component. Here is an example:

<div style={styles.content}>
<Route path={`${this.props.match.url}/summary`} render={props => <ETFViewer {...props} />} />
<Route path={`${this.props.match.url}/proxy`} render={props => <Proxy {...props} />} />                      
</div>
like image 132
KaiC Avatar answered Oct 06 '22 14:10

KaiC