How can I create a browser router in ReactJS?

Viewed 53

I'm finding it difficult to create a Browser Route in React. Here is what I want to do:

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Navbar from './components/navbar/Navbar';
import RecipeList from './containers/recipe-list/RecipeList';
import Recipe from './containers/recipe-details/RecipeDetails';
import Footer from './components/footer/Footer';
import Error from './components/error/Error';
import './App.css';

export default function App() {
  return (
    <div>
      <Navbar />
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={RecipeList} />
          <Route path="./containers/recipe-details/RecipeDetails" component={Recipe} />
          <Route component={Error} />
        </Switch>
      </BrowserRouter>
      <Footer />
    </div>
  );
}


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

export default function Recipe() {
  return (
    <div>
      <Link to="../../containers/recipe-details/RecipeDetails">Recipe</Link>
    </div>
  );
}

The problem comes in my Recipe component which I want to create a separate route for. Thanks in anticipation of your response.

2 Answers

The path to the Route is the link in the browser that will show up that component and not the path to the component in your directory structure, you can set up your Route and Link like below

export default function App() {
  return (
    <div>
      <Navbar />
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={RecipeList} />
          <Route path="/recipe" component={Recipe} />
          <Route component={Error} />
        </Switch>
      </BrowserRouter>
      <Footer />
    </div>
  );
}

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

export default function Recipe() {
  return (
    <div>
      <Link to="/recipe">Recipe</Link>
    </div>
  );
}

Your Route path will match what you'd like your url to look like

  • <Route exact path="/" component={RecipeList} /> will open your RecipeList component with this website: www.yourwebsite.com/
  • <Route path="/recipe" component={Recipe} /> will open your Recipe component with this website: www.yourwebsite.com/recipe

I don't know exactly how you'd like it, but I'd imagine you want a more simple path like:

<Switch>
     <Route exact path="/" component={RecipeList} />
     <Route path="/RecipeDetails" component={Recipe} />
     <Route component={Error} />
</Switch>

and accessing your route through a link is as simple as:

<Link to="/RecipeDetails">Recipe</Link>
Related