Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - `component` vs `render` in Route

I have two doubts regarding usage of Route from react-router-dom(v4.3.1):

  1. When do we use component vs render in Route:

    <Route exact path='/u/:username/' component={ProfileComponent} />
    <Route exact path='/u/:username/' render={() => <ProfileComponent />} />
    
  2. How to access the variable username in the URL in both ways?
like image 229
Sreekar Mouli Avatar asked Jul 07 '18 20:07

Sreekar Mouli


People also ask

What is the difference between render and component in React router?

render makes the component mount just once, then re-render when required. The component stays in the background — this means that anything you put in componentDidMount , constructor , or, for example, shouldComponentUpdate , will run only once! Also, because the component doesn't unmount, you may run into data leakage.

What is render in route React?

render: funcInstead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop function has access to all the same route props (match, location and history) as the component render prop.

Which component is used to render a route?

You generally use the render prop when you need some data from the component that contains your routes, since the component prop gives no real way of passing in additional props to the component.


1 Answers

When you pass a component to the component prop, the component will get the path parameters in the props.match.params object, i.e props.match.params.username in your example:

class ProfileComponent extends React.Component {
  render() {
    return <div>{this.props.match.params.username}</div>;
  }
}

When using the render prop, the path parameters can be accessed through the props given to the render function:

<Route
  exact
  path='/u/:username/'
  render={(props) => 
    <ProfileComponent username={props.match.params.username}/>
  }
/>

You generally use the render prop when you need some data from the component that contains your routes, since the component prop gives no real way of passing in additional props to the component.

like image 195
Tholle Avatar answered Oct 25 '22 21:10

Tholle