Daniel Zuzevich Daniel Zuzevich - 1 year ago 80
React JSX Question

React Router Child Rendering Issue

I am two steps away from an aneurysm attempting to figure this out(help me). For the Javascript wizards of Stack Overflow, this should be no problem. I believe the issue at hand is a minor fix that I just am not seeing due to lack of experience.

Current Setup

  • Using React with Webpack, Express, React Router, and Node JS locally on my own machine.

  • There are three components/files that need to be discussed at the moment, which I will list below. The quick description of each will give an easy background on their purpose before you see the code.

    -> Index.js (Main file that handles the final render).

    -> App.js (The "Main" Component).

    -> Messages.js (The child component I am attempting to render inside of App.js).

The Issue
Everything works, but when I click the link to go to the messages component, the title of the app, and the link dissappear. However, it does show all of the information I put inside the return statement in the messages component, which is a good thing.

My Question
I believe I am just misunderstanding the basic principal of nested routes within React Router. My initial understanding was that if I setup my code like it currently is, the Messages component would appear INSIDE of the app component on link click, and would not remove any of the text associated in the parent App component.

The following material I have provided to help out is as ordered,

- Screenshot of the App Component rendered on the screen, showing the title and the link to messages.
- Screenshot of the view after the messages link is clicked.
- Component Code.

App on initial load

View after the link is clicked

// App.js
import '../assets/stylesheets/base.scss';
import React, { Component } from 'react';
import { Link } from 'react-router';

export default class App extends Component {
render() {
return (
<div id="title">
<h1>My App</h1>
<div id="navigation">
<li><Link to="/messages">Messages</Link></li>

// Messages.js

import React, { Component } from 'react';

const Messages = () => {
return (
<div id="messages">
<h1>My Messages</h1>

export default Messages;

// Index.js
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './components/App';
import Messages from './components/messages';

<Router history={browserHistory}>
<Route path="/" component={App}/>
<Route path="/messages" component={Messages}/>
), document.getElementById('root'))

Answer Source

You need to model that project as a single page application (SPA) for that. Something like that

<Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="/messages" component={Messages}/>
      <Route path="*" component={NoMatch}/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download