Spdexter Spdexter - 1 year ago 80
Javascript Question

React router issue

Hi i have problems getting routes work.

Here is my route.js

import React, { Component } from 'react';
import Home from './Home';
import Add from './Add';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'
export default (


<Router history={browserHistory}>
<IndexRoute component={Home}/>
<Route path='/' component={Home} />
<Route path='/add/' component={Add} />
</Router>
);


Here is App.js

import React, { Component } from 'react';
import routes from './route';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'

class App extends Component {
constructor(props) {
super(props);

}


render() {
return (
<Router history={hashHistory}>{routes}</Router>
);
}
}

export default App;


Here is Add.js

import React, { Component } from 'react';
import Header from './Views/Header';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'


import './styles/App.css';
import './styles/layout.css';

class Add extends Component {
constructor(props) {
super(props);

}

render() {
return (
<div className=" ">
<Header />
<h2> Add a cake </h2>
</div>
);
}
}

export default Add;


I haven't added Home.js because Home works just fine.

but when i click '/add' url points to 'http://localhost:3000/add#/' but nothing happens.

can you please help.

Thanks

Answer Source

The problem is you are using a Router within a Router in App.js, one with hashHistory and the other with browserHistory.

Change your Routes to

import React, { Component } from 'react';
import Home from './Home';
import Add from './Add';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'
export default (
    <Router  history={browserHistory}>
        <IndexRoute component={Home}/>
        <Route path='/' component={Home} />
        <Route path='/add' component={Add} />
      </Router>
      );

and app.js to

import React, { Component } from 'react';
import routes from './route';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'

class App extends Component {
  constructor(props) {
    super(props);

  }


  render() {
    return (
         <div>{routes}</div>
      );
  }
}

export default App;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download