I'm using createHashRouter on a vite project for easier deployment to Github Pages. But vite is not recognizing the routes.
Is there any other configuration also required for this? Please see the code below
Home Component
function Home() {
return (
<div className="App">
Home
</div>
)
}
export default Home
About Component
function About() {
return (
<div className="App">
About
</div>
)
}
export default About
index.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import Home from './Home'
import About from './About'
import './index.css'
import { createHashRouter, RouterProvider } from 'react-router-dom';
const router = createHashRouter([
{
path: '/',
element: <Home />,
},
{
path: '/about',
element: <About />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
)
Navigation to work in browser as expected
The correct way to access the URL is http://127.0.0.1:5173/#/about instead of http://127.0.0.1:5173/about or http://127.0.0.1:5173/#about
The behaviour was not documented well in react-router which caused the confusion.
Related
I've been working with the react router dom and I keep seeing a blank white page on my screen.
App.js:
import React from 'react';
import HelloWorld from './HelloWorld';
import { HashRouter as Router, Route } from 'react-router-dom';
import Home from './Home';
function App() {
return (
<Router>
<Home />
<Route path="/notes" exact element={HelloWorld} />
</Router>
);
}
export default App;
Home.js:
import React from 'react';
import { Link } from 'react-router-dom';
function Home() {
return (
<div>
<Link to="/testHome" style={{ color: 'blue', fontSize: '20px' }}>
Go to Notes
</Link>
</div>
);
}
export default Home;
HelloWorld.js:
import React from 'react';
function MyComponent() {
return (
<div>
<h1>Hello world</h1>
</div>
);
}
export default MyComponent;
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
When I simply display the components in app.js, I can clearly see the hello world element on the screen, the problem is when I use react router. When I use react router I just see a blank white page. Can anyone help me solve the issue?
There are a couple issues:
The Route component isn't being rendered by a Routes (or other Route component in the case of nested routes).
The element prop takes a React.ReactNode prop value, a.k.a. JSX.
To resolve import the Routes component and wrap the Route component and render the HelloWorld component as JSX.
import React from 'react';
import HelloWorld from './HelloWorld';
import {
HashRouter as Router,
Routes, // <-- import Routes
Route
} from 'react-router-dom';
import Home from './Home';
function App() {
return (
<Router>
<Home />
<Routes> // <-- wrap rendered routes
<Route
path="/notes"
element={<HelloWorld />} // <-- render as JSX
/>
</Routes>
</Router>
);
}
I am a bit new to react and I am facing a problem with the Router.
The routing works when I enter the URL directly on the browser, however when I click on the link, the URL changes on the browser (e.g http://localhost:8080/contactus), but the content don't get updated (But if I do a refresh, it gets updated).
Here is my github repo:
https://github.com/Arefaat18/Project
Here is my MainComponent.js
import React, { Component } from 'react';
import {TransitionGroup, CSSTransition} from 'react-transition-group';
import {Switch, Route, Redirect,withRouter,BrowserRouter as Router} from 'react-router-dom';
import Header from './HeaderComponent';
import ContactUs from './ContactUsComponent';
import AboutUs from './AboutUsComponent';
import Home from './HomeComponent.js';
import {connect} from 'react-redux';
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Router>
<Header />
<TransitionGroup>
<CSSTransition classNames="page" timeout={300}>
<Switch>
<Route path="/home" component={Home} />
<Route exact path = "/contactus" component ={ContactUs} />
<Route exact path = "/aboutus" component ={AboutUs} />
<Redirect to="/home" />
</Switch>
</CSSTransition>
</TransitionGroup>
</Router>
</div>
);
}
}
export default withRouter(Main);
And here is my App.js file
import React, { Component } from 'react';
import Main from './components/MainComponent';
import './App.css';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {ConfigureStore} from './components/configureStore';
const store = ConfigureStore();
class App extends Component {
render() {
return (
<Provider store={store}>
<BrowserRouter>
<div className="App">
<Main />
</div>
</BrowserRouter>
</Provider>
);
}
}
export default App;
and here is the relevant dependancies
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-redux": "^7.2.1",
"react-redux-form": "^1.16.14",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.4",
And here is my ContactUsComponent, the other components are just the same with different text
import React, { Component } from 'react';
class ContactUs extends Component {
render(){
console.log("RENDER");
return (
<div>
<h1> Contact Us</h1>
</div>
);
}
}
export default ContactUs;
Thanks in advance.
Well I also stuck with the same Issue but in react 18 our component in index.js file is by default wrapped in react strict mode
like this:
<React.StrictMode>
<App/>
</React.StrictMode>
I removed React strict Mode tags then it worked perfectly fine for me
Right, you've extraneous Routers declared, your header component has one. Remove this Router.
It is because each Router provides a routing context, and each component subscribing to a routing context gets the context from the closest router. The router providing context to the header wasn't rendering any routes so that is why the URL would change but the router actually rendering the Routes wasn't being notified that it should render a different path.
class Header extends Component {
constructor(props) {
...
}
...
render() {
return (
<React.Fragment>
{/* <Router> */} // <-- Remove this Router Component
<Navbar dark expand="md">
...
</Navbar>
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
...
</Modal>
{/* </Router> */}
</React.Fragment>
);
}
}
I ran into a similar problem. I used Link in the components, but I imported it from #reach/router.
As a result, I replaced
import { Link } from "#reach/router"
with
import { Link } from "react-router-dom"
in each component; and everything worked as it should
I just finish the course Front-End Web Development with React. I think you are learning this course too so I see nothing wrong with your code, possibly the problem is inside your ContactUs component. If you can provide your ContactUs code then I can debug it
I had the same issue as well but I had to wrap my App.js with BrowseRouter in the index.js file.
import {BrowserRouter as Router} from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Router>
<App />
</Router>
);
I have a super simple react app like so.
index.tsx
App.tsx
Main.tsx
Home.tsx
index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter as Router } from "react-router-dom";
import { ApolloProvider } from "react-apollo";
import client from "./utils/client";
ReactDOM.render(
<Router>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</Router>,
document.getElementById('root')
);
App.tsx
import React from 'react';
import Main from "./Main";
function App() {
return (
<Main />
);
}
export default App;
Main.tsx
import React from 'react';
import { Switch, Route, Link } from "react-router-dom";
import Home from "./Home";
const Main:React.FC = () => {
return (
<div>
<Switch>
<Route exact path='/' component={Home} />
</Switch>
</div>
);
};
export default Main;
Home.tsx
import React, {useContext} from 'react';
import { Link } from "react-router-dom";
const Home:React.FC = () => {
return (
<div>
<h1>Home</h1>
<Link to='http://google.com'> Google</Link>
</div>
);
};
export default Home;
I have an App.test.tsx with a dummy test just to run it.
import React from 'react';
import { render, screen } from '#testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
expect(true).toBeTruthy
});
If I run the test with yarn test
I get an error:
Invariant failed: You should not use <Link> outside a <Router>
The Link I have is in Home.tsc which is surrounded by <Router> in index.tsx
I'm I doing something work here.
The app runs without any errors.
This error only appears when I run the test
There are two solutions below, the first is to add <Router> component into your test case. The second option is to switch from <Link> to a simple anchor tag.
Option 1:
You can add <Router> component into your test also, so it won't missing there as:
test('renders learn react link', () => {
render(<Router>
<App />
</Router>);
expect(true).toBeTruthy
});
Option 2:
Also you can change from <Link> component to a simple anchor tag because it creates the same end result based on your code from:
<Link to='http://google.com'> Google</Link>
To the following in <Home> component:
Google
Then at the end you can keep your original test case.
I've been working on a react single page app and have been trying to get the routing to work.
I believe the routing itself actually works however the page does not load the correct content unless the page is manually reloaded. Back and forward browser arrows also work.
For example I can navigate to localhost:3000 fine and the content is loaded correctly but when I press a button to navigate to localhost:3000/contacts nothing is displayed unless I refresh the page. Once manually refreshed the contacts page shows up. What gives?
index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom';
// Import App component
import App from './App'
// Import service workers
import * as serviceWorker from './serviceWorker'
// Render App component in the DOM
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root')
)
serviceWorker.unregister()
App.tsx
// Import necessary dependencies
import React from 'react'
import Routes from './Routes'
// Create App component
function App() {
return (
<div className="App">
<Routes />
</div>
)
}
export default App
history.tsx
import { createBrowserHistory as history} from 'history';
export default history();
Home/Home.tsx
import React, { Component } from "react";
import history from './../history';
import "./Home.css";
export default class Home extends Component {
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
Contact/Contact.tsx
import React, { Component } from 'react';
class Contact extends Component {
render() {
return (
<div>
hello world
</div>
);
}
}
export default Contact;
Routes.tsx
import React, { Component } from "react";
import {BrowserRouter, Router, Switch, Route } from "react-router-dom";
import Contact from "./Contact/Contact";
import Home from "./Home/Home"
import history from './history'
export default class Routes extends Component {
render() {
return (
<div>
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/Contact" component={Contact} />
</Switch>
</Router>
</div>
)
}
}
Any help greatly appreciated
I think there's some extra code that might be causing conflict. You're defining the Router from react-router-dom twice:
Once here, in index.tsx
ReactDOM.render(
<Router> // here
<App />
</Router>
, document.getElementById('root')
)
and then again in Routes.tsx
<Router history={history}> // here
<Switch>
<Route path="/" exact component={Home} />
<Route path="/Contact" component={Contact} />
</Switch>
</Router>
You have to drop one of them, they're probably conflicting each other
Update
In addition to that, I think you should not use the history object directly from your export, but access it through the HOC withRouter. Then, you'd wrap
So you'd do something like this
import React, { Component } from "react";
import { withRouter } from 'react-router-dom'
import "./Home.css";
class Home extends Component {
const { history } = this.props
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
export default withRouter(Home)
I think the issue here is that you need to wrap your pages with withRouter() like so:
import React, { Component } from "react";
import history from './../history';
import "./Home.css";
import { withRouter } from 'react-router-dom'; //<---------- add this
class Home extends Component {
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
default export withRouter(Home); //<-------------- and add this
You will need to do the same on your Contact page as well.
Why do you have two routers?
I guess you simply need to remove the Router either in index.tsx or in Routes.tsx
According to you file naming I would remove the Router in Routes.tsx
It seems like you are using the history package for navigation. If you are using the react-router v5, then you may have to downgrade the history package to 4.10.1 until the history package developers issue a new release with the fix. As of writing this, the latest release version of history package is v5.0.1, and if you see a new release than this, you can try with that version first to see if it works, before doing the downgrade to 4.10.1
Issue Link -> https://github.com/remix-run/history/issues/804
I have an application that uses the same layout for all routes... except one.
One route will be completely different than all others.
So the entire application will have a menu, body, footer, etc.
The one-off route will not have any of that and be a completely separate thing.
How should I set this kinda thing up in a react app? Everything I've ever seen/done always has one main wrapping element that has the routes rendered as children.
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import configureStore from './store'
import App from './components/App'
// import registerServiceWorker from './registerServiceWorker'
import { unregister } from './registerServiceWorker'
const preloadedState = window.__PRELOADED_STATE__ ? window.__PRELOADED_STATE__ : {}
// console.log('window.__PRELOADED_STATE__', window.__PRELOADED_STATE__)
delete window.__PRELOADED_STATE__
const Store = configureStore(preloadedState)
const rootEl = document.getElementById('root')
ReactDOM.hydrate(
<Provider store={Store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
rootEl
)
if(module.hot){
module.hot.accept('./components/App', () => {
ReactDOM.hydrate(
<Provider store={Store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
rootEl
)
})
}
// registerServiceWorker()
unregister()
App.js
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
// Components
import AppHelmet from './AppHelmet'
import Notices from './Notices'
import Header from './Header'
import Body from './Body'
import Footer from './Footer'
// Site state
import { getSiteInfo } from '../store/actions/siteInfo'
import { REACT_APP_SITE_KEY } from '../shared/vars'
// CSS
import '../css/general.css'
class App extends Component {
initialAction() {
this.props.getSiteInfo(REACT_APP_SITE_KEY)
}
componentWillMount() {
// On client and site info has not been fetched yet
if(this.props.siteInfo.site === undefined){
this.initialAction()
}
}
render() {
return (
<div>
<AppHelmet {...this.props} />
<Notices />
<div className="body">
<Header />
<Body />
</div>
<Footer />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
siteInfo: state.siteInfo,
user: state.user
}
}
const mapDispatchToProps = (dispatch) => {
return {
getSiteInfo: (siteKey) => dispatch(getSiteInfo(siteKey))
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
Body.js
import React, { Component } from 'react'
import { Switch, Route } from 'react-router-dom'
import routes from '../shared/routes'
class Body extends Component {
render() {
return (
<Switch>
{routes.map((route, i) => <Route key={i} {...route} />)}
</Switch>
)
}
}
export default Body
So, as you can see the index.js entry point will render <App />. <App /> will render the main layout, including <Body />, which renders all routes and content.
Cool.
But seeing as I don't want this one-off to render the <App /> layout, I'm not sure how to set this up from index.js. I'm sure it's simple and I'm just not seeing the answer.
One way to achieve what you want is to listen to the router.
You can add the listener into the components you want to hide.
When the listener detects you're on a view where you do not want the components to show, simply don't render them for that view.