m.awais
m.awais

Reputation: 23

React Router Issues with homepage path

I made a react app. But when I'm writing

npm start

the result written as below:

You can now view pizza-app in the browser.

  Local:            http://localhost:3000/react-pizza-app   
  On Your Network:  http://192.168.56.1:3000/react-pizza-app

Note that the development build is not optimized.
To create a production build, use npm run build.

The problem is that it will show only Header component not showing the others. Here is my main App.js code.

import React, { useState } from "react";
import Header from './Header';
import {
  BrowserRouter as Router,
  Switch,
  Route
} from "react-router-dom";
import Customize from "./Customize";
import Checkout from './Checkout';

function App() {

  const [ingredients, setIngredients] = useState({
    basil: false,
    cheese: false,
    mushroom: false,
    olive: false,
    pineapple: false,
    tomato: false,
  });

  return (
    <>
    <Header />
    <Router>
    <Switch>
          <Route exact path="/">
            <Customize ingredients = {ingredients} setIngredients={setIngredients} />
          </Route>
          
          <Route path="/checkout">
          <Checkout ingredients = {ingredients} />
          </Route>
        </Switch>
    </Router>
    </>
    
  );
};

export default App;

If I reset my homepage to ".", then it's shows all components. And application will run smoothly. I will paste my package.json file also.

"name": "pizza-app",
  "homepage": "http://editorawais.github.io/react-pizza-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.1",
    "@testing-library/user-event": "^12.2.0",
    "framer-motion": "^2.9.4",

I want to deployed this app to github as well. Please help me what is the problem actually. And what should be the solution.

Upvotes: 1

Views: 1554

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

I believe you need to set the basename of the Router to match the sub-directory it is being served from, i.e. "/react-pizza-app".

basename

The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash.

function App() {
  const [ingredients, setIngredients] = useState({
    basil: false,
    cheese: false,
    mushroom: false,
    olive: false,
    pineapple: false,
    tomato: false,
  });

  return (
    <>
    <Header />
    <Router basename="/react-pizza-app">
    <Switch>
          <Route exact path="/">
            <Customize ingredients = {ingredients} setIngredients={setIngredients} />
          </Route>
          
          <Route path="/checkout">
          <Checkout ingredients = {ingredients} />
          </Route>
        </Switch>
    </Router>
    </>
    
  );
};

Upvotes: 1

Related Questions