1

I am trying to use React Router on my MERN stack app am having trouble since all routes are rendering the same component

Router(index.jsx):

import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import Home from './components/home.jsx'
import App from './app.jsx'
import ContactsIndex from './components/contacts/contactsIndex.jsx'

if(typeof window !== 'undefined') {
    ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={App}>
          <IndexRoute component={Home} />
          <Route path='contacts' component={ContactsIndex}/>
        </Route>
    </Router>, document.getElementById("root"));
}

App.jsx

import React from 'react'
import { Router, Route, Link } from 'react-router'
import Home from './components/home.jsx'

export default class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return(
      <div>
        <p>Text</p>
        {this.props.children}
      </div>
    )
  }
}

Entry from express into React:

app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine())
app.set('view engine', 'jsx')

app.get('*', (req,res) => {
  res.render('index.jsx')
})

No Matter what route I visit(even ones that are not defined) the contents of App.jsx are rendered. It seems that I'm doing something incorrectly here which is making hashHistory not work. I'm using React-Router 2.6.1

1 Answer 1

0

If you look at your code you can see that your router is first mounting the app component, right

<Router history={hashHistory}>
    <Route path='/' component={App}>
...

Then you have this is inside your App component:

{this.props.children}

So the way that react router is working is that it is using App.js as a container inside which you are mounting the other components.

So for example, if you go to /contacts your tree will look like this

<div>  //This is the app component
    <p>Text</p>
    <ContactsIndex> // Whatever route you render goes here...
</div>

If you want to render just a new tree at each route then with this current implementation you can keep the App.js div as a wrapper for your pages.

Sign up to request clarification or add additional context in comments.

1 Comment

This makes sense. However, the issue is that at each route ONLY the contents of app.jsx are being rendered and no other components are being rendered. It seems like this.props.children is undefined and thus no children are being rendered. I must be passing them in incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.