0

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.

João Durante
  • 273
  • 5
  • 14

2 Answers2

4

React Router is the exact thing you're looking for

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