Alex Alex - 2 months ago 18
React JSX Question

React.js generate dynamic routes for the same component with different data

I have the following routes.jsx:

ReactDOM.render((
<Router>
<Route component={Wrapper} >
<Route path="/" component={Home} />
<Route path="projects" component={Projects} />
<Route path="projects/Margam" component={Margam} />
<Route path="projects/Margam2" component={Margam2} />
<Route path="projects/Margam3" component={Margam3} />
</Route>
</Router>
), document.getElementById('app'));


Margam, Margam2 and Margam3 are the same components but just with different data. This is essentially a list of projects which has the same design but different content.

Is it possible to generate routes dynamically passing different data but always using the same component?

Margam:

import React from 'react';

import Video from './video.jsx';

class Margam extends React.Component {
render () {
return (
<div>
<h2>Margam</h2>
<Video />
</div>
);
}
}

export default Margam;


Margam2:

import React from 'react';

import Video from './video.jsx';

class Margam extends React.Component {
render () {
return (
<div>
<h2>Margam 2</h2>
<Video />
</div>
);
}
}

export default Margam2;

Answer

You could do something like this :

<Route component={Wrapper} >
     <Route path="/" component={Home} />
     <Route path="projects/:id" component={Projects} />
</Route>

And then in Projects component you can access to the id with {this.props.params.id} and depending on that id you can show different components.

Something like this :

render() {
    let Margam = (this.props.params.id == "margam") ? <Margam /> : "";
    let Margam2 = (this.props.params.id == "margam2") ? <Margam2 /> : "";

    return (
        <div>
            {Margam}
            {Margam2}
        </div>
    );
}

Hope this help.