Hallemon
Hallemon

Reputation: 161

React app on gh-pages : can not link to local files

If I create a react app, and in this app there's a link to a local html file, once this app published on gh-pages, for some reasons said link doesn't lead anywhere, it just redirect the user on the same page he was in before clicking the link .

For exemple:

If I create a simple app with CRA like so :

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        I'm the homepage
        <a id='testlink' href='html2.html'> Go to the second page </a>
      </div>
    );
  }
}

export default App;

And in the public folder I create a new html file "html2.html" that simply says

I am the second app !

And that's all, a simple app supposed to jump from index.html to html2.html when a link is clicked. Well this app works fine when tested with npm start, it works fine if launched via the static html file provided with npm run build, but when deployed on gh-pages, suddendly the link does not lead anywhere.

Here is the app described above deployed on ghpages

One workaround this problem would be to upload all the apps separately on gh-pages, or to use react router, but I wanted to know if I was just missing something. Thanks for your help.

Upvotes: 2

Views: 1115

Answers (1)

Soroush Chehresa
Soroush Chehresa

Reputation: 5678

On React projects you should use react-router to handle routes and change pages.

Simple example:

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/topics">Topics</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);

const About = () => (
  <div>
    <h2>About</h2>
  </div>
);

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>Rendering with React</Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>Components</Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic} />
    <Route
      exact
      path={match.url}
      render={() => <h3>Please select a topic.</h3>}
    />
  </div>
);

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
);

export default BasicExample;

Upvotes: 1

Related Questions