1

I have my following routes.jsx

import React from 'react';
import { Route, Router, IndexRoute } from 'react-router';
import ReactDOM from 'react-dom';

import App from './index.jsx';
import Test1 from './test1.jsx';
import Test2 from './test2.jsx';
import TestWrapper from './wrapper.jsx';

import url from './url.json';

var routes = url.url.map(function(el){
   return (<Route key={el} path={el} component={Test1} />);
});

ReactDOM.render((
  <Router>
    <Route path="/" component={App} >
        {routes}
    </Route>
  </Router>
), document.getElementById('app'));

I am going to have a list of projects that will be using always the same component hence:

var routes = url.url.map(function(el){
   return (<Route key={el} path={el} component={Test1} />);
});

and a test1.jsx as follow:

import React from 'react';
import data from './data.json';

class Test1 extends React.Component {
  render () {
    return (
      <div>
        // if is route "title1" load title1
        // if is route "title2" load title2
        // if is route "title3" load title3
      </div>
    );
  }
}

export default Test1;

my url.json is:

{
  "url": [
    "title1",
    "title2",
    "title3",
    "title4",
    "title5"
  ]
}

I am fairly new to react, how can I pass to "test1" content based on the url? Ideally I will have a separate json file for the content.. Ex. if I am on localhost:8080/title1 I would like content loaded only for title1.

Aessandro
  • 5,517
  • 21
  • 66
  • 139
  • 1
    Why dont you create 5 components that load title1, title2 and so on. And call them on url accordingly using router. You are kind of trying to implement your own router it seems. – Umang Gupta Aug 21 '16 at 12:46
  • I think it's very repetitive to have 5 components that are identical and only different in data... I was hoping there could be a dynamic way of achieving the same result, using a loop perhaps... – Aessandro Aug 21 '16 at 12:50
  • If they are different in data only. You can pass data via props from router itself. So You will have one component that takes some props and renders according to props. – Umang Gupta Aug 21 '16 at 12:57
  • 1
    You could use the injected location from the router to get the pathname and load the data based on the pathname passed to the component. [https://github.com/reactjs/react-router/blob/master/docs/API.md#injected-props](https://github.com/reactjs/react-router/blob/master/docs/API.md#injected-props) – Norm Crandall Aug 21 '16 at 12:58
  • But wouldn't that be a bad practice ? Because urls and component will be coupled – Umang Gupta Aug 21 '16 at 13:03
  • See this http://stackoverflow.com/questions/27864720/react-router-pass-props-to-handler-component and comment by ciantic- "you could add a stateless component syntax (just lambda) there also, it's pretty short ()}/>" – Umang Gupta Aug 21 '16 at 13:12

0 Answers0