Get Component from react-router by path

Viewed 615

How to get Component from react-router v4 by path?

I'm looking for a way to get the component that configured before, by path.

Forexample I have got this Route:

import React from 'react';
import UserScreen from './UserScreen';
...
<Route path='/user/:id' component={UserScreen}/> 

Now I want to get the UserScreen Component by the path. Something like this:

getComponentByPath(path){
   // looking for this section 
}

render(){
  const component = getComponentByPath('/user/12');
  return (<component />);
}

I'm looking for the Component object.

1 Answers

you can use BrowserRouter react router v4 and render a component with corresponding route.

<BrowserRouter>
    <Switch>
      <Route path='/user/:id' component={UserScreen}/> 
   </Switch>
</BrowserRouter>

make a UserScreen.js:

class UserScreen extends Component {

render() {

    return (
    <div>hello world</div>
    )
  }
}
Related