Search code examples
reactjsreact-routerreact-router-component

React-Router 1.0.0-rc4 - dynamic router - params not working


Problem:

This dynamic router works, except when there is a dynamic link involving params.

Specifically:

I can hard code a link or type in the browser:

 <Link to="Inventory/All-Vehicles">All Vehicles</Link>
  http://localhost:3000/Inventory/All-Vehicles

And with code:

const { id } = this.props.params;
console.log({ id } );

The console shows:

{id: "All-Vehicles"}

However, with a dynamic link ...

< Link to={ this.props.item.linkTo } className="">{ this.props.item.title }< /Link>

which produces:

< a class="" href="#Inventory/All-Vehicles" data-reactid=".0.0.0.0.0.0.0.0.0.0.$2.1.0.$0.0.0.0">All Vehicles< /a>

the browser shows

localhost:3000/#/Inventory/All-Vehicles

for an instant and then resets itself to (the page does not reload)

localhost:3000/#/Inventory

With console showing:

Object {id: undefined}

I re-wrote this question per Jordan's suggestion below.
I hope it is not too lengthy. I use alt flux as my store

routes.js:

import React, { Component, PropTypes } from 'react';
import Router, { Route } from 'react-router';
// alt
import connectToStores from '../../node_modules/alt/utils/connectToStores';
import NavStore from '../alt/stores/nav-store';
import NavActions from '../alt/actions/nav-actions';

class Routes extends Component {

  constructor(props) {
    super(props);
    this.state = {
      routes: []
    };
  }

  static getStores() {
    return [NavStore];
  }

  static getPropsFromStores() {
    return NavStore.getState();
  }

  componentDidMount() {
    const clientId = this.props.clientId;
    NavActions.getAll(clientId);
  }

  fetchNonRootComponent(paths) {
    let result;
    paths.map((path) => {
      if (path !== '/') {
        result = path;
      }
    });
    return result;
  }

  fetchMenuSystem(data) {
    const self = this;
    const currRoutesState = this.state.routes;
    const routes = data === undefined ? this.props.items : data;

    routes.map((route) => {
      // set paths up first
      let currPaths = [];
      if (route.paths !== undefined) {
        currPaths = route.paths;
      } else {
        currPaths.push(route.linkTo);
      }
      // Components - first check for ecomMods
      let currComponent;

If it is in the routes.js file it probably has something to do this section:

      if (route.ecomMod !== undefined) {
        currComponent = require('../components/pages/' + route.ecomMod);
        // clear out currPath if this is an ecom Module
        // and start a new currPaths array
        currPaths = [];
        if (route.parentId === null) {
          currPaths.push(route.ecomMod);
        } else {

          // multi-purpose :id, eg.
          // Inventory/Used-Vehicles
          // Inventory/Stock#1234

          currPaths.push(route.ecomMod + '/:id');
        }
      } else {
        const nonRootComponent = self.fetchNonRootComponent(currPaths);
        currComponent = require('../components/pages/' + nonRootComponent);
      }

      currPaths.map((currPath) => {
        const props = { key: currPath, path: currPath, component: currComponent };
        currRoutesState.push(<Route { ...props } />);
      });

      if (route.childNodes !== undefined) {
        self.fetchMenuSystem(route.childNodes);
      }
    });
    return currRoutesState;
  }

  fetchRoutes() {
    const result = this.fetchMenuSystem();
    return (
      <Route component={ require('../components/APP') }>
        { result }
        <Route path="SiteMap" component={ require('../components/pages/Site-Map') }/>
        <Route path="*" component={ require('../components/pages/Not-Found') }/>
      </Route>
    );
  }

  render() {
    if (this.props.items.length === 0) return <div>Loading ...</div>;
    const routerProps = {
      routes: this.fetchRoutes(),
      createElement: (component, props) => {
        return React.createElement(component, { ...props });
      }
    };
    return (
      <Router { ...routerProps } history= { this.props.history } />
    );
  }
}

Routes.propTypes = {
  clientId: PropTypes.string.isRequired,
  history: PropTypes.object.isRequired,
  items: PropTypes.array.isRequired
};

export default connectToStores(Routes);

navItems.json:

{
  "data": [
    {
      "id": 1,
      "parentId": null,
      "linkTo": "/",
      "paths": [
        "/",
        "Home"
      ],
      "title": "Home",
    },
    {
      "id": 2,
      "parentId": null,
      "linkTo": "About-Us",
      "title": "About Us",
    },
    {
      "id": 3,
      "parentId": null,
      "ecomMod": "Inventory",
      "linkTo": "Inventory",
      "title": "Inventory",
      "childNodes": [
        {
          "id": 30,
          "parentId": 3,
          "ecomMod": "Inventory",
          "linkTo": "Inventory/All-Vehicles",
          "title": "All Vehicles",
        }
        ]
    }
  ]
}

Solution

  • SOLVED

    Nearly a day later, I solved this and the mistake I made was so stupid and so blatantly obvious I cannot believe I did not see it.

    As I suspected, the dynamic router is fine. The problem was with the drop down menu. Which I suspected as a hard-coded link on a page worked.

    Illustratively, this is how the Inventory route is created:

    <Route path="Inventory" component="Inventory">
       <Route path="Inventory/All-Vehicles" component="Inventory" />
    </Route>
    

    So it is plain to anyone that an All-Vehicles click will 'bubble up' to it's parent, if the dam parent has a route handler event to it, and that is exactly what mine had.

    So, in my case, this parent link:

      <li id={ this.props.item.id }
          ......
          onClick={ this.routeHandler.bind(this, { newLinkTo } ) } >
        <span className="">{ this.props.item.title }</span>
          // get the children
          <div>{ this.fetchSubMenu(this.props.item) }</div>
      </li>
    

    is now:

      <li id={ this.props.item.id }
          ......
      >
        <Link to={ newLinkTo } className="">{ this.props.item.title }</Link>
          // get the children
          <div>{ this.fetchSubMenu(this.props.item) }</div>
      </li>
    

    Lesson learned: If you have a route handler up the node tree, it will take over any route changes the children try to make.