I'm starting in React and I'm curious about about if have any way to change a page without reload all the html, changing only a content component for example. I know that there is a way to change the component without change the url but I thought that if the url change too the application would be better.
Asked
Active
Viewed 3,693 times
0
-
That's what `react-router` allows you to do, client side routing: https://github.com/ReactTraining/react-router – Jayce444 Jun 15 '19 at 04:34
-
react-router v4 is your answer. – Yash Gadle Jun 15 '19 at 09:04
2 Answers
4
Here, how you can achieve what you're looking for.
First, wrap your app with BrowserRouter
import { BrowserRouter } from "react-router-dom";
import React from 'react';
class App extends React.Component {
return (){
return (
<BrowserRouter>
<SomeComponent />
</BrowserRouter>
)
}
}
Now just use the Route
and Link
. Route told the application which component to render on the basis of the current route and Link changes the URL without reloading the whole page
import { Route, Link, Switch } from "react-router-dom";
import React from 'react';
import {Circle, Square} from './someFileWithComponents';
class SomeComponent extends React.Component {
render(){
return (
<div>
<Link to='/circle' >Circle</Link>
<Link to='/square' >Square</Link>
<Switch>
<Route path='/circle' component={Circle} />
<Route path='/square' component={Square} />
</Switch>
</div>
)
}
}

Siraj Alam
- 9,217
- 9
- 53
- 65
0
React Router is what you looking for
const AppRouter =()=>(
<BrowserRouter>
<div>
<Header/>//where Header components contains the navigation
<Switch>
<Route path="/" component={BookListPage} exact={true} />
<Route path="/create" component={AddBookItem} />
<Route path="/edit/:id" component={EditBookItem} />
<Route path="/help" component={HelpPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;

DeCoder
- 9
- 2