Error refresh router react router - react-router

When I click on the link that contains url products/new I can access the new product page and it works fine, but if I refresh the page it returns Uncaught SyntaxError: Unexpected token <.
How can I resolve this?
Page product new
import React from 'react';
class ProductNew extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<div>
<div><h1>ProductNew</h1></div>
</div>
);
}
}
module.exports = ProductNew;
page products
import React from 'react';
import { Link } from 'react-router';
class Products extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div><h1>Products</h1></div>
<Link to="/products/new">new</Link>
</div>
);
}
}
module.exports = Products;
Page App
render((
<Router history={createBrowserHistory()}>
<Route path="/" component={Layout}>
<IndexRoute component={Home} />
<Route path="/products" component={Products}/>
<Route path="/products/new" component={ProductNew}/>
</Route>
</Router>
), document.getElementById('app'));

I had a similar problem, my App.js path were relative.
So when I loaded the app page from home path everything worked well, but when I tried to load from a link like yours "/product/new", I received an error like yours. When I put an absolute path, it worked fine.
I was using webpack to bundle the file and webpack-dev-server to run the development env and there is no physical files when you use webpack-dev-server hot loader (by default), it's a thing there is easy to fall in.
Edit:
this guy's question has 2 updates on it, with the same problem as you and has a better answer/info than that I gave to you.

whe you are using nested path for component Like http://127.0.0.1:8000/dashboard/myprojects then you should must add absolute path for your css and js in main index file..for example in laravel index.php.blade file add absolute path Like this: <'script src="{{ mix('js/app.js') }}">
</'script>

Related

Local page links (<a href='#' />) aren't working with HashRouter

I wanted to add multiple pages to my React website so I started using the HashRouter import from react-router-dom. Since then only my main page loads and I am no longer able to use local links in the page. I can't redirect the user to specific areas on the main page which i used to be able to do before I started using the Router import. This website also uses github pages if that affects anything.
I am currently using the <a> tags like this:
<a className="nav-link" href="/#about-me">
About Me
</a>
with the URL appearing as this with no content below it
http://localhost:3000/#about-me
I have also tried using the <Link> tag but it just ends up reloading the page.
<Link className="nav-link" to="/#about-me">
About Me
</Link>
With this URL appearing instead:
http://localhost:3000/#/#about-me
How do I get my page to scroll down to the id rather than reload or load a blank page?
Main code snippets for reference:
Home.js snippet
const Home = () => {
return (
<div className='main'>
<section className='section-welcome'>
<Introduction />
</section>
<section id='about-me' className='section-about-me'>
<AboutMe />
</section>
</div>
);
};
export default Home;
Main.js
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './Pages/Home.js';
import NoPage from './Pages/NoPage.js';
const Main = () => {
return (
<Routes>
<Route path='/' element={<Home />}></Route>
<Route path="*" element={<NoPage />} />
</Routes>
);
}
export default Main;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { HashRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router>
<App /> {/* The various pages will be displayed by the `Main` component. */}
</Router>
</React.StrictMode>
);
The problem is with how the code runs with GitHub pages, not the references.
Currently, whenever a link is clicked in the NavBar the website tries to load the URL as root/{href from <a> tag}. This conflicts with GitHub pages as it searches links under the githubname.github.io/project-name/ and the program is trying to display githubname.github.io/#.
In order to fix this, you need to add a basename in the <Router> tag which forces the page to load at /project-name/#.
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { HashRouter as Router } from 'react-router-dom';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router basename={process.env.PUBLIC_URL}>
<App /> {/* The various pages will be displayed by the `Main` component. */}
</Router>
</React.StrictMode>
);
Relevant Links for more info
https://maximorlov.com/deploying-to-github-pages-dont-forget-to-fix-your-links/
https://create-react-app.dev/docs/deployment/#building-for-relative-paths

Changing landing page for react website , localhost

I deployed one website on localhost, with npm build / react, and I would like to select another landing page.
However I'm a newbie working with React and I don't know where to find the routes for the pages. I have the following codes in the public/Index.html, public/manifest.json, and package.json from root folder.
I tried modifying the homepage in package.json to another folder/.ts/.tsx files but without any success.
Any idea in how to find the routes to other pages and how to set the landing page to them for localhost server ?
you don't touch the public folder for routes, and assuming you want to link to another page like you want to go from / to /about then you need to do this:
this will be your home page - app.tsx
import { BrowserRouter, Routes, Route} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About/>} />
</Routes>
</BrowserRouter>
);
}
this will be your about file, about.tsx
import { Link } from 'react-router-dom';
function About() {
return (
<div>
<nav>
<Link to="/">Home Page</Link>
</nav>
</div>
);
}
To understand more about routes please check the documentation below
React router V6

React Router + GH Pages, refresh breaking app

This isn't happening on my local server,
but when I push my create-react-app to gh-pages and try to reload anything besides the home page, or navigate directly to a routed page, the page breaks and the URL repeatedly grows looking like this...
https://hellocentral.live/about/?p=/&q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/....
Here is my file with my routes...
import React from "react";
import "./SiteContainer.scss";
import HeaderContainer from "../HeaderContainer/HeaderContainer";
import { Route, Switch } from "react-router-dom";
import About from "../About/About";
import Home from "../Home/Home";
import Music from "../Music/Music";
import Footer from "../Footer/Footer";
import Merch from "../Merch/Merch";
import Pics from "../Pics/Pics";
import Contact from "../Contact/Contact";
export const SiteContainer = () => {
return (
<div className="site-container">
<HeaderContainer />
<Switch>
<Route path="/about" component={About} />
<Route path="/merch" component={Merch} />
<Route path="/music" component={Music} />
<Route path="/pics" component={Pics} />
<Route path="/contact" component={Contact} />
<Route path="/" component={Home} />
</Switch>
<Footer />
</div>
);
};
export default SiteContainer;
here is my repo
https://github.com/monstaro/hc3/tree/master/src
The site is https://www.hellocentral.live
Any help would be appreciated!
You need to wrap the Switch component in a Router component. To do this, you need to import it from the react-router-dom package:
import { HashRouter as Router } from 'react-router-dom'
...
<Router basename={process.env.PUBLIC_URL}>
<Switch>
...
</Switch>
</Router>
I gave HashRouter as example because GH Pages does not support the other router, BrowserRouter. Probably, MemoryRouter or StaticRouter do work, but I am not sure.
Since your domain is https://www.hellocentral.live, you need to set segmentCount to 0 here.
Guess you're using an older version of rafgraph/spa-github-pages cited in a blog or something. I would recommend updating index.html with the latest version of the script and 404.html with this script.
From the docs,
Note that if you are setting up a Project Pages site and not using a custom domain (i.e. your site's address is username.github.io/repo-name), then you need to set pathSegmentsToKeep to 1 in the 404.html file in order to keep /repo-name in the path after the redirect.

React-router-dom: Very simple nested routing does not work

I have searched through different tutorials and multiple stackOverflow questions. And none of which, helped me solve a very basic problem:
Implement nested routes with react-router-dom
Here's my code so far:
App.js
<Route exact path="/home" name="Home" component={DefaultLayout} />
DefaultLayout.js
<Route path="/home/users" component={Users} />
When I go to /home/users, I get a blank screen because react-router-dom is looking-up the definition of that route inside App.js instead of searching it inside DefaultLayout.js..
So I have two questions:
QUESION 1: What am I doing wrong exactly?
QUESTION 2: How does react-router-dom know that it should look for the nested route inside DefaultLayout.js instead of inside App.js?
It has been two days and I still cannot solve this simple problem.
Any help is very much appreciated.
EDIT 1: I have started a new project just for the sake of implementing a very simple nested routing:
App.js
import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import ParentComponent from "./nestedComponents/ParentComponent";
function App() {
return (
<div>
<BrowserRouter>
<Switch>
<Route exact path="/home" name="Home" component={ParentComponent} />
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
ParentComponent.js
import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";
export default function ParentComponent() {
return (
<div>
PARENT COMPONENT
<Switch>
<Route path="home/nestedComponentOne" component={nestedComponentOne} />
<Route path="home/nestedComponentTwo" component={nestedComponentTwo} />
</Switch>
</div>
);
}
nestedComponentOne.js
import React from "react";
export default function nestedComponentOne() {
return <div>NESTED COMPONENT 1</div>;
}
nestedComponentTwo.js
import React from "react";
export default function nestedComponentTwo() {
return <div>NESTED COMPONENT 2</div>;
}
But, I still get a blank screen whenever I try to access a nested component...
You have this problem:
React-router urls don't work when refreshing or writing manually
The simplest fix is to replace the BrowserRouter with a HashRouter

Navigate in code with react-router-dom 4.0?

Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.
I've search StackOverflow but haven't found any answers that work with 4.0. Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:
import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);
I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':
<Route path="/" render={({ match, context}) => {
console.log('match:', match);
console.log('context:', context);
Edit
In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:
<Route path="/" render={({ match, context, history}) => {
Is there a way to get to this from outside a route? For example a navbar component that will navigate to other components, but is not inside a Route itself...
If I understand your question, this is how you make a link programaticaly.
class Test extends React.Component {
handleClick() {
console.log(this.context);
this.context.router.history.push('/some/path');
},
render() {
return (
<div onClick={handleClick}>
This is div.
</div>
)
}
}
Test.contextTypes = {
router: React.PropTypes.object.isRequired
}
ReactDOM.render(
<Test />,
document.getElementById("app")
);
Had to read into the docs more. The history object is only passed as a property using the component (or other) attributes on a Route. Apparently need to include the 'history' package and use createBrowserHistory and pass it to the Router, then specify the component in a Route. I think this should work fine since exact isn't specified...
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
ReactDOM.render( (
<Router history={ history }>
<Route path="/" component={ App } />
</Router>
),
document.getElementById('root')
);
Before I just had <App/> inside <Router> and didn't have access to those properties.
Why don't you just wrap your div in the link instead of trying to circumvent it and make your life easier?
<Link to="/" >
<div className="to-component">go to component</div>
</Link>