Creating a 404 page with HashRouter - javascript

I have created a NotFound page that should be displayed when I type a non-available URL. I must use HashRouter in my app. The code below works whey I type example.com/#/somethingwrong but not for example.com/somethingwrong.
index.js
const app = (
<React.StrictMode>
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>
</React.StrictMode>
);
app.js
return (
<ScrollToTop>
<Switch>
<Route path="/" exact component={MainScreen} />
<Route path="*" component={NotFound} />
</Switch>
</ScrollToTop>
);

Since it is HashRouter you have to put path="/(asterik symbol)" instead of path="(astertik symbol)". It works for me.

Related

Multiple html pages in react-router-dom

I have the following BrowserRouter in my main index.js React file:
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />}>
<Route path="clients" element={<ClientsList />} >
<Route path="client/:clientID" element={<Client />} />
</Route>
<Route path="*" element={<NoContent />} />
</Route>
<Route path="iframe-invoice/:invoiceID" element={<InvoiceFrame />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
When I load the paths /, clients and client/<clientID> the app correctly display the content of the relative modules in the /app/public/index.html file (as expected):
What I'm trying to do is to render the content of iframe-invoice/:invoiceID in a separate html page, something like /app/public/iframeinvoice.html.
The full HTML content of the module InvoiceFrame will be loaded from a database (both html head, body, styles, etc..) and it require to be rendered outside of the /app/public/index.html file.
Either in an apposite html file with only this:
<noscript>You need to enable JavaScript to tead the invoice</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/bundle.js"></script>
or in some other way.
So basically the React app on iframe-invoice/:invoiceID will have to:
Request the full HTML page of :invoiceID, with an API call, from the backend
Cache this HTML in the browser localstorage
Render this HTML in the browser (probably with dangerouslySetInnerHTML)
Next time the same invoice is requested load it from the localstorage and render it
Is it possible with React?

Why routes not working for deployed react-website? [duplicate]

My previous website only shows the home page when the home tab is clicked, then if you click my navbar brand, it says 404. This website worked on a create-react-app with npm start, but it doesn't work here, nor on the build. I don't know what is wrong with the app, maybe the router setup is messed up, I don't know. I have linked the App and Index pages where I have the router setup. If you need any more information, just ask me for more information.
Thank You
Index
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'
import App from './App';
import './styles/index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
App
import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import About from "./routes/About";
import Contact from "./routes/Contact";
import Home from "./routes/Home";
import Project from "./routes/Project";
const App = () => {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<Home />}></Route>
<Route path="/about" element={<About />}></Route>
<Route path="/project" element={<Project />}></Route>
<Route path="/contact" element={<Contact />}></Route>
</Routes>
</>
);
};
export default App;
If deploying to GitHub, ensure there is a "homepage" entry in package.json for where you are hosting it in Github.
Example:
"homepage": "https://github.com/amodhakal/portfolio",
Switch to the HashRouter since GitHub pages doesn't support the tech used by the BrowserRouter.
index
import React from 'react';
import ReactDOM from 'react-dom/client';
import { HashRouter } from 'react-router-dom'
import App from './App';
import './styles/index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<HashRouter>
<App />
</HashRouter>
</React.StrictMode>
);
For more details see the create-react-app docs for deploying to GitHub Pages and notes on client-side routing.
I faced this similar routing problem in ReactJs when I used gh-pages.
My Problem: Routes are working fine at my local system but when I deployed my web app to gh-pages I wasn't able to go to any page directly using the URL.
Example: ayushjaink8.github.io/cfhelper was working and I am able to go to other pages from within the web app too but when I directly type ayushjaink8.github.io/cfhelper/dashboard in the URL, it will show github 404 error page.
Solution: I resolved the above problem by using <HashRouter/> and adding the homepage tag in the package.json like homepage: "/<repository-name>/#".
gh-pages also follows this # rule in its URL routing. So it won't show any 404 error page if you write ayushjaink8.github.io/cfhelper/#/<any-route-of-your-app>.
Everything else remains the same in my codebase. I haven't used any useHistory() function or <BrowserRouter /> or any other thing as well. This simple hack works for all cases.
Instead of /<repo-name>, your homepage becomes /<repo-name>/#. That's all.
Here goes my sample code:
import { Routes, Route, HashRouter } from "react-router-dom";
<HashRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth/login" element={<Login />} />
<Route path="/auth/signup" element={<Signup />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/contests/create" element={<CreateContest />} />
<Route exact path="/contests/join" element={<JoinContest />} />
<Route path="/contests/live" element={<LiveContest />} />
<Route path="/practice" element={ <Practice /> } />
<Route path="/analyze" element={ <Analyze /> } />
<Route path="/verify" element={<VerifyEmail />} />
<Route path="/profile/edit" element={<EditProfile />} />
</Routes>
<Footer />
</HashRouter>
Package.json Sample Code:
{
"name": "cfhelper",
"homepage": "/<your-github-repo-name>/#",
"version": "1.0.0",
"private": true,
}
// add basename to your browserRouter component
<BrowserRouter basename='/reponame'>
<App/>
<BrowserRouter/>
Figured it out. It's because of the url structure.
https://umair-mirza.github.io/safetyapp/
means you have to define a route for /safetyapp
like this:
<Route path='/safetyapp' element={<Home />} />

Why my sub url can not be accessed directly after a deploy my react project on server?

I built a react project. The react version is 17.0.2 and the react-router-dom version is 6.2.1. I used "npm run build" and deployed the build folder to the server. The site can be visited and the site can jump to any specific page when I click the link button on the homepage or any other pages. But except homepage, when I refresh the page or I use the URL to visit this page, it will show "not found". This situation doesn't appear on local when I code.
What is causing this problem and how to address it?
Thanks!
The following is part of my code on index.js and app.js
index.js
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
app.js
function App() {
return (
<div>
<Header />
<Routes>
<Route path="/" element={ <Landingpage />} exact />
<Route path="/aboutus" element={ <AboutUsPage />} />
<Route path="/myservice" element={ <MyServicePage />} />
<Route path="/portfolio" element={ <PortfolioPage />} exact />
<Route path="/portfolio/:projectId" element={ <ProjectPage />} />
<Route path="/contact" element={ <ContactPage />} />
</Routes>
</div>
);

react-cookie-consent does not work on html pages in public folder

I am using react-cookies-consent to display cookies and it is working without any problem on every component until I needed to add HTML pages to the public folder for SEO reasons now the cookies consent will not be displayed on these pages. Any suggestion on how should I approach this problem.
import React from 'react';
import ReactDOM from 'react-dom';
import { render } from 'react-snapshot';
import {BrowserRouter as Router} from 'react-router-dom';
import Routes from "./routes";
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import CookieBanner from "./CookieBanner";
import * as serviceWorker from './serviceWorker';
import C5 from "./images/konfigurator/C5.webp";
import HelmetMetaData from "./HelmetMetaData";
render(
<React.StrictMode>
<Router>
<CookieBanner />
<Routes />
{/*<App />*/}
</Router>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
class Routes extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<HelmetMetaData />
<Switch>
<Route exact path="/" render={() => {window.location.href="Home.html"}} />
<Route path="/Main" component={App}/>
<Route path="/About" render={() => {window.location.href="About.html"}}/>
<Route path="/impressum" render={() => {window.location.href="impressum.html"}}/>
<Route path="/blog" render={() => {window.location.href="blog.html"}}/>
<Route path="/Questions" render={() => {window.location.href="Questions.html"}} />
<Route path="/Answers" render={() => {window.location.href="Answers.html"}} />
<Route path="/info" render={() => {window.location.href="info.html"}} />
<Route component={Error}/>
</Switch>
</div>
);
}
};
export default Routes;
Update:
I just tried the possibility to render a component in HTML page I started with a simple example but it doesn't work
<script src="https://unpkg.com/react#16.13.1/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16.13.1/umd/react-dom.development.js" crossorigin></script>
<!--<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>-->
<script type="text/jsx">
var NewComponent = React.createClass({
render : function (){
return (
<h1>New year welcoming</h1>
)
}
})
ReactDOM.render(<NewComponent />, document.getElementById('banner'));
</script>
</body>
Yes i included <div id="banner"></div> just right after the <body>
No errors given it just doesn`t render
You're basically talking about having a mixed-domain. One SPA (your React app) and some non-spa HTML pages.
To make this work you'd have to run React in both scenarios, which is what you've tried in the last picture.
I would recommend foregoing the "HTML" pages route, it is difficult to maintain. Instead, you can use Gatsby to create those few static pages. You can even re-use components between your existing React code-base and the React-based Gatsby part.
Using static HTML pages doesn't improve SEO by default. If you're running into performance problems you should have a look at Server-side-rendering or static site generation (like Gatsby)

React.js Uncaught Error: _registerComponent(...): Target container is not a DOM element

Hi I am getting this error:
main.js:808 Uncaught Error: _registerComponent(...): Target container is not a DOM element.
I have visited this question, but I cannot figure out what is wrong with what I am doing.
Here is the code I have right now:
routes.js:
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
</Route>
);
app.js
const store = configureStore();
render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('app')
);
homepage.js
class HomePage extends React.Component {
render() {
return (
<div id="app">
Hello
</div>
);
}
}
export default HomePage;
I think that I am missing something easy but I am not sure what it is. I have tried modifying my code to match the answers of that other question but it didnt work out. Thank you for any help
The error says that document.getElementById('app') operation didn't find any corresponded html node in the page document. You have to create a <div id="app"></div> directly in your index.html so document.getElementById('app') could find it. Your <div id="app"> in HomePage container is useless as it's unavailable in DOM during React app initialization.
Also, be sure to inject your <script> with bundled React app after <div id="app"></div> (inject that <script> to the end of the body tag to be safe).

Categories