2

I am using react router with my application and everything works fine locally. Below is my code. The issue is when I host it online it is in a my-application subdirectory:

https://www.example.com/my-application

This is breaking the code and it is not functioning as it should.

can anyone advise how to fix this issue? If there is anything unclear please feel free to ask. I have tried countless approaches but cannot get it to work. One answer can be seen here.

the issue I am getting is that with the current code it navigates to https://www.example.com/test as opposed to https://www.example.com/my-application/test. I thought if I hardcoded in the url it would work but this also breaks the application.

The code below is slightly whittled down to remove superfluous code.

import React, { Component } from 'react';
import styled from 'styled-components'
import { Route, Switch } from 'react-router-dom'


const Home = ({ avatarUrl }) => {
  return (
      <div>
         <Route exact path="/" component={Overview}/>
         <Route path="/test" component={Test}/>
      </div>
  );
};

class App extends Component {

  render() {

    return (
      <section>
        <Nav avatarUrl={ this.props.avatarUrl }/>
        <Switch>
          <Route path="/example" component={Example}/>
          <Route path="/" render={()=><Home
            avatarUrl={ avatarUrl }
          />}/>

        </Switch>
      </section>
    )
  }
}

export default App
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

2 Answers2

0

Apply config changes pacakage.json add homepage page as your folder name

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

To solve this I just did two things:

  1. Added "hostname": "https://www.example.com/my-application" at the top of package.json.
  2. Added basename="my-application" to the BrowserRouter e.g. <BrowserRouter basename="my-application">

Note: I created the project using create-react-app. I am using react version 18 and react-router version 6.

Gaurish Gangwar
  • 395
  • 4
  • 14