Benji Durden Benji Durden - 3 years ago 103
React JSX Question

React Router: Render new view without page refresh

React Route Load Test

Hello! What I'm trying to do is rework my react-router so the NavLink renders a completely new page on click, instead of rendering at the bottom of the div, as shown in the gif above.

Here's the content of my main App.js component:

import React, { Component } from 'react';
import './App.css';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Home from './Home.js';
import About from './About.js';
import September from './September.js';
import Trilogy from './Trilogy.js';

class App extends Component {
render() {
return (
<Router>
<div>
<Switch>
<Route exact path = '/' component={Home} />
<Route path = '/about/' component = {About} />
<Route path = '/september/' component = {September} />
<Route exact path = '/september/trilogy/' component = {Trilogy} />
</Switch>
</div>
</Router>
);
}
}
export default App;


The Home component's code, which holds the NavBar that's used in the Home Page.

import React, { Component } from 'react';
import {BrowserRouter as Router, NavLink, Switch, Route} from 'react-router-dom';
import logo from './logo.png';
import About from './About.js';
import September from './September.js';
import Trilogy from './Trilogy.js';

let NavBar = () => {
return (
<div>
<h2 className = "container2"><NavLink to = '/about/'>About</NavLink> </h2>
<img src = {logo} className = "somersetLogo" alt = "somersetLogo" />
<h2 className = "container" ><a href="mailto:contact@somersetproductions.co" className = "mailto">Contact</a></h2>
</div>
)
}

class Home extends Component {
render(){
return (
<Router>
<div>
<NavBar />
<Switch>
<Route exact path = '/about/' component = {About} />
</Switch>
</div>
</Router>
)
}
}

export default Home;


Any idea what went wrong? Any help would be appreciated! Thanks!

Answer Source

If you are using react router v4 or above it should be something like this.

import { Link } from 'react-router-dom';

<Link to='/about'>
    About
</Link>

Why you are defining router again in Home component which is not needed. Keeping route configuration in App component would be enough. Hope this helps. Happy coding !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download