Github pages HashRouter not displaying components - javascript

My react app on github page doesn't render the components using HashRouter, blank page on "/" and 404 error on "/about".
this is my app.js
function App() {
return (
<div className="Container-fluid" id="div2">
<HashRouter basename="/Landing-Page">
<Header />
<Routes>
<Route path="/thankyou" element={<ThankYou />} />
<Route
exact
path="/"
element={
<div className="Container">
<SignUp validate={validate} />
<EbookInfo />
</div>
}
/>
<Route path="/about" element={<About />} />
</Routes>
</HashRouter>
</div>
);
}
on homepage it shows .../Landing-Page/ as expected
but on other page it shows .../about instead of .../Landing-Page/about.
I have gh-pages setup.
my github page https://alexhmar.github.io/Landing-Page/
my repo https://github.com/alexhmar/Landing-Page/tree/master
I have also tried this with <Router basename={process.env.PUBLIC_URL} but it's the same issue.

When using Github Pages and React Router Dom you need to use the Hash Router.
Replace your import by import { HashRouter as Router } from "react-router-dom"; and it should work.
Github Pages isn't configured for single page applications, if you try to access /bar, it will try to find a bar.html file and thus give you a 404. By using the hash router, when you navigate to links it will go to /#bar so Github Pages won't redirect you and React Router Dom will see it as navigating to /bar as you'd expect it, as long as you're using the Link component or the hooks.

I deployed on Heroku instead of Github pages,now it's working fine.

Related

Using App component as a home page in react (path "/")

this is my first question here and I apologize upfront if it already been answered. I'm studying react and I started a project as well, and my question is: how can I make my App component a home page? Or do I have to create a component to do so? I´m using react-router-dom for navigation, like the code below, and keep getting the message "No routes matched location "/"". How can I set a route to it? I would like to use the App component instead of using a page component named home. If I did something wrong about the post, again, I'm sorry. Thanks in advance.
import React from 'react'
import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom'
import Blog from './pages/Blog'
import About from './pages/About'
import Faq from './pages/Faq'
import Market from './pages/Market'
import GlobalStyle from './styles/global'
function App() {
return (
<Router>
<GlobalStyle/>
<header>
<nav>
<Link to="/products">Nosso produtos</Link>
<Link to="/blog">Diário do Café</Link>
<Link to="/faq">Cafaq - perguntas frequentes</Link>
<Link to="/about">Sobre nós</Link>
</nav>
</header>
<Routes>
<Route path="/products" element={<Market />} />
<Route path="/blog" element={<Blog />} />
<Route path="/faq" element={<Faq />} />
<Route path="/about" element={<About />} />
</Routes>
<footer> Footer </footer>
</Router>
)
}
export default App
The App component is already your default component. Any path will render the App component as long as you have wrapped the App component with the BrowserRouter component
// In index.js
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
so I assume your point is to keep the navbar visible regardless of the current path and that is already done because anything placed in the App component will be rendered, and the paths content will be changed based on the elements specified in the Routes.
In case, you want to create a separate Home component, then you will create a Route with a path '/' and the Home Component element.
Make sure that you understand how routing works to avoid any bugs in the future
Hope you found it helpful.
The route element with path ="/" will be your home page
Try with this;
<Route path='/' exact element={<Home/>} />

Page is rendering but not components although everything compiles and styles can be added outside the component

So here is a snippet of code from my App.js,
return (
<div className="app">
<Router>
{!user ? (
<LoginScreen />
) : (
<Switch>
<Route path='./profile'>
<ProfileScreen />
</Route>
<Route exact path="/">
<HomeScreen />
</Route>
</Switch>
)}
</Router>
</div>
Now when I click on the profile button, it takes me to a blank profile page and there are no errors, and everything compiles. Here is the ProfileScreen page code,
import React from 'react'
import './ProfileScreen.css'
function ProfileScreen() {
return (
<div className='profileScreen'>
<h1>
this is the profile screen
</h1>
</div>
)
}
console.log("hello")
export default ProfileScreen
Now the issue here is that every time I refresh the page the console.log("hello") (a test) shows up in developer tools! It also shows up in the main page before I am taken to the profile page. Also in the css file, I can change the entire background color using
* {
background-color:black;
}
So something is clearly working as I can change the background of the profile page but whenever I target the profileScreen class nothing shows up and my h1 never shows up even without styling when there should be text showing up. I am very new to reactJS and react-router-dom so I would appreciate any help! thank you.
I'm certain your profile path is incorrect. AFAIK react-router-dom v5 doesn't use relative path routing, it uses absolute path routing, so "./profile" is an invalid path. Update it to be "/profile".
<Switch>
<Route path="/profile">
<ProfileScreen />
</Route>
<Route exact path="/">
<HomeScreen />
</Route>
</Switch>

React BrowserRouter works when navigating on localhost. Refreshing a not-home-page when deployed throws 404 not found

My code is using React-router-dom. It works on gh-pages with all navigation within the page. However, accessing by adding /blog to the url or refreshing the /blog page returns 404 not found. The app is structured like this:
App.js
function App() {
return (
<div className="App" >
<header className="App-header" width="100%" >
<BrowserRouter basename="/">
<Switch>
<Route component={Main} exact path="/" />
<Route component={Blog} exact path="/blog" />
</Switch>
</BrowserRouter>
</header>
</div>
);
}
export default App;
Blog.js:
function Blog() {
return (
<div className="App" >
<header className="App-header" width="100%" >
<div id="home" width="100%">
<BrowserRouter id="blog">
<div>
<Route component={AllPosts} exact path="/blog/" />
<Route component={OnePost} exact path="/blog/:slug" />
</div>
</BrowserRouter>
<SidebarIfBrowser />
</div>
</header>
</div>
);
}
export default Blog;
Do I miss something essential?
The issue looks to be about how you are using nested routes.
First in App.js remove the exact because you don't want it to be exact
// App.js
<Switch>
<Route component={Main} exact path="/" />
<Route component={Blog} path="/blog" />
</Switch>
Now in your Blog.js there are a few edits you need to make. First is to replace your BrowserRouter with Switch. You only want to have 1 BrowserRouter in your entire app and it should be in the high level which is what you have in your App.js.
Then you want to change the paths in your Routes. You dont need to include /blog/ in them since they are nested routes within the /blog route from your App.js Technically what you have before would of been /blog/blog
// Blog.js
function Blog() {
return (
<div className="App" >
<header className="App-header" width="100%" >
<div id="home" width="100%">
<Switch>
<div>
<Route component={AllPosts} exact path="/" />
<Route component={OnePost} exact path="/:slug" />
</div>
</Switch>
<SidebarIfBrowser />
</div>
</header>
</div>
);
}
export default Blog;
note this only works for react-router v5 and if you are using v6 then there are some other changes you would need
This is a well known problem when deploying a SPA to github pages. To make the client side routing work, every request must be redirected to the index.html and this behavior is not implemented by github pages.
This is explained in the create react app documentation. It seems that you have two solutions :
switch from using HTML5 history API to routing with hashes
follow this guide. You must add a custom 404.html page to your project and add a custom script tag to your index.html page. I already used this solution, it worked well for me.
This happens because you're making a GET request on the server for a non existing route. You can fix this by following the steps bellow:
1. Point the home page in your package.json
{
...
"homepage": ".",
...
}
2. Create a .htaccess file and place it in the root directory of your app
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R=301,L]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
NOTE: This is valid only when you deploy your React app. On development you can access any route by only using React Router.

routing within an app using react router to move to another page

I am trying to use router in my app
so I used react-router-dom, but I am facing issues,
researched and found this link but still not helping me.
Invariant failed: You should not use <Route> outside a <Router>
can you tell me how to use route and link
i need to redirect to another page.
providing my code snippet and sandbox below.
https://codesandbox.io/s/still-smoke-uf731
let Channel = ({ channelName, channelString, onClick, active }) => (
<div onClick={onClick} className=" col-lg-2 col-md-4 col-sm-6 ">
<div>router</div>
<Router>
<Link to={"/here"}> here</Link>
<Switch>
<Route path="/auth" />
<Route path="/" />
</Switch>
</Router>
<div
className="channel-button"
style={{
backgroundColor: active === channelString ? "orange" : ""
}}
>
<p>{channelName}</p>
</div>
</div>
);
Use exact as an attribute in your home route like the following code.
<Router>
<Link to={"/here"}> here</Link>
<Switch>
<Route exact path="/" />
<Route path="/auth" />
</Switch>
</Router>
I checked your sandbox. Looks like a good start, but you messed some things up.
Here is my fork of your sandbox: https://codesandbox.io/embed/staging-fast-rr5k9
First, don't put react components in the containers, put them in the components folder and import them.
What was going on was, that you had brand new <Router> for every page you had. So I pulled the Router out. Its also not imported correctly. It should be
import { BrowserRouter as Router } from "react-router-dom";
So you pretty much need something like this
<div>
<Link to={"/bbc-news"}>BBC</Link>
</div>
<div>
<Link to={"/cnbc"}>CNBC</Link>
</div>
<Switch>
<Route
key={"fbbc-news"}
path="/bbc-news"
render={p => <Channel channelName="BBC" channelString="bbc-news" />}
/>
<Route
key={"cnbc"}
path="/cnbc"
render={p => <Channel channelName="CNBC" channelString="cnbc" />}
/>
</Switch>
</Router>
Where Channel component renders whats inside the channel. the key in Route is important, because it makes React properly trigger componentDidMount, which calls the thunk action which fetches (that one is perfect).
Then to access the results from fetch, which you have placed in Redux =>
const mapStateToProps = state => ({ json: state.json });
You don't need a lot of the things you had, so I have removed them, like the onClick, which was trying to do react routers job
You can try this:
import Stats from './containers/stats';
<Route
exact={true}
path="/"
component={Stats}
key="Mykey"
/>

how to link in a page with React Router v1.0.0

I want to link to a specific section section of a page with react router a lot like how anchor tags would work in html. However, I couldn't find solutions with React Router version 1.0.0.
Currently, i have my router like this:
let history = createHashHistory({
queryKey: false
});
<Router history={history}>
<Route path="/" component={a}/>
<Route path="/b" component={b}/>
<Route path="/c" component={c}/>
<Route path="/d" component={d}/>
<Route path="/e" component={e}/>
<Route path="/f" component={f}/>
<Route path="/g" component={g}/>
</Router>
and I am trying to link to a specific section in the components like
<Link to="/b#{div_id}"> Go to section with div_id is component {b} </Link>
There is currently an open issue on GitHub for this. It doesn't appear to be supported, but it should be supported when using HistoryLocation when this issue is fixed.
EDIT
This is no longer supported.

Categories

Resources