Can't get react-router-dom to work (seeing blank page) - javascript

This is my App component that has 3 child components: Home, Contact and Procedures. I'm trying to make each child component into its own url route.
However right now I'm just seeing a blank page
FYI- I'm using react-router-dom#6.0.2
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import Home from './Home.js'
import Contact from './Contact.js'
import Procedures from './Procedures.js'
import './App.css';
function App() {
return (
<BrowserRouter>
<Routes>
<Route exact path="/" component={Home} />
<Route path="/procedures" component={Procedures} />
<Route path="/contact" component={Contact} />
</Routes>
</BrowserRouter>
);
}
export default App;

In react-router-dom version 6 you should use element instead of component, also be sure to reference the element you want to render as JSX. By the way, there is no longer any "exact" attribute.
Should look like this on your code:
<Route path="/" element={<Home />} />

Related

react-router-dom 6.8.1 and react 18.2.0 <Link> only updated URL

I'm using react-router-dom 6.8.1 and react 18.2.0 and trying to set up browser router using the createBrowserRouter() and createRoutesFromElements() functions. I'm then rendering my browser router using the <RouterProvider> component, and the front page of my website displays fine (the App component does). For some reason, any react-router-dom <Link> components I place in my components appear on the front page, but when I click them, only the URL changes, and it does not update the UI. What's weird is that if I use an <Outlet>, the UI from the child routes will display when I click any links, but that's not what I want. I need to navigate to a separate page.
Here's where I'm creating the browser router:
import * as ReactDOM from 'react-dom/client';
import {
createBrowserRouter,
createRoutesFromElements,
Route,
RouterProvider,
} from 'react-router-dom';
import App from './app/app';
import ParticipantProfile from './app/profiles/participantProfile';
const browserRouter = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route path="profile" element={<ParticipantProfile />} />
</Route>
)
);
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(<RouterProvider router={browserRouter} />);
Here's where I create my <Link>:
import { Link } from 'react-router-dom';
import { createTheme } from '#mui/material/styles';
const theme = createTheme();
function App() {
return <Link to="profile">Profile</Link>;
}
export default App;
I'm tried rendering the <BrowserRouter> component itself instead of using createRoutesFromElements, but same results. Changing the path from profile to /profile also seems to do nothing.
If you want each route to map to a different component (without layout nesting), there is no need to wrap them all under a single <Route> element.
<>
<Route path="/" element={<App />} />
<Route path="/profile" element={<ParticipantProfile />} />
</>
Alternatively, only specify the element on the child route.
<Route path="/">
<Route index element={<App />} />
<Route path="profile" element={<ParticipantProfile />} />
</Route>

What is wrong with the structure of my 'BrowserRouter', 'Routes' and 'Route' in my function App()?

I am attempting to follow a tutorial while learning React.JS and I am running into an issue because the tutorial is using an older version of React and I am stuck trying to figure out how to use BrowserRouter, Routes, and Route.
Can anyone assist me in trying to re-structure the code so it works with the updated version of React? I have tried reading through documentation and tried to mix around a few solutions with no success. Any help is much appreciated!
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "./components/navbar.component.js";
import PortfolioList from "./components/portfolio-list.component";
import EditPortfolio from "./components/edit-portfolio.component";
import CreatePortfolio from "./components/create-portfolio.component";
import CreateUser from "./components/create-user.component";
function App() {
return (
<Routes>
<Navbar />
<br/>
<Route path="/" exact component={PortfolioList} />
<Route path="/edit/:id" exact component={EditPortfolio} />
<Route path="/create" exact component={CreatePortfolio} />
<Route path="/user" exact component={CreateUser} />
</Routes>
);
}
export default App;
The following is the 'error' I'm generating on runtime:
Error: [Navbar] is not a 'Route' component. All component children of
'Routes' must be a 'Route' or 'React.Fragment'
Only Route components and React.Fragments can be a child of the Routes component, and vice-versa. Move the non-Route components out of Routes. The Route component API also changed in version 6, there is no longer render and component props, the routed components are passed to the element prop as JSX, and routes are now always exactly matched, so there's no longer the exact prop as well.
function App() {
return (
<>
<Navbar />
<br/>
<Routes>
<Route path="/" element={<PortfolioList />} />
<Route path="/edit/:id" element={<EditPortfolio />} />
<Route path="/create" element={<CreatePortfolio />} />
<Route path="/user" element={<CreateUser />} />
</Routes>
</>
);
}
you can use the "BrowserRouter" tag followed by the "Switch" tag then you can now use the "Route" tag to specify the path of each component
you can use the "BrowserRouter" tag followed by the "Switch" tag then you can now use the "Route" tag to specify the path of each component.
return (
<>
<BrowserRouter>
<Switch>
<Route path="/" exact component={DashBoard} />
<Route path="/specialistes" exact component={Specialistes} />
<Route path="/findgarages" exact component={FindGarage} />
<Route path="/garages" exact component={Garages} />
</Switch>
</BrowserRouter>
</>
)````

React routing not working v4

I'm trying to route multiple pages using BrowserRouter. Many of the guides online are outdated and do not work with Reactv4. Here's what I'm doing:
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom'
import SignIn from './components/SignIn';
import SignUp from './components/SignUp';
import ForgotPass from './components/ForgotPass';
ReactDOM.render((<BrowserRouter>
<Switch>
<Route path="/" component={SignIn}/>
<Route path="/signup" component={SignUp}/>
<Route path="/forgot" component={ForgotPass}/>
</Switch>
</BrowserRouter>), document.getElementById('root'));
And then I create hyperlinks to those pages using:
Forgot password?
But when I click the hyperlink it just loads the same page again.
Also: I've seen some guides use the App component, I wasn't sure if that is something predefined in React and if it was needed, as I need the SignIn component to be the default page.
Put the exact flat on your root path. Otherwise it will match in the switch before it gets to the lower routes.
<Switch>
<Route exact path="/" component={SignIn}/>
<Route path="/signup" component={SignUp}/>
<Route path="/forgot" component={ForgotPass}/>
</Switch>
OR move it to the end:
<Switch>
<Route path="/signup" component={SignUp}/>
<Route path="/forgot" component={ForgotPass}/>
<Route path="/" component={SignIn}/>
</Switch>

React Router - Stay at the same page after refresh

I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:
<Provider store={store}>
<Router path="/" history={browserHistory}>
<Route path="/home" component={App}>
<Route path="/" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')
In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.
There is code from App.jsx
class App extends Component {
render() {
return (
<div className="app-comp">
<Navigation />
<div> {this.props.children}</div>
</div>
)
}
}
I also attach gif which shows my problem.
https://gifyu.com/image/boMp
In backend i use Firebase if it's important.
Thanks in advance.
I found the reason of my problem. I use also Firebase in my project and it causes the problem.
Thanks guys for help.
EDIT ======================================================================
Mabye I will write how I've fixed my problem and what was the reason of it.
So i was checking if user is logged in or not in auth method. And there if user was authorized I was pushing / to browserHistory.
It was mistake because every refresh method was executing and then also redirection was called as well.
Solution is just to check if during executing auth method I'm on Signin page or not. If it is Signin page then I'm pushing / to browserHistory but if not then just don't push anything.
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
let currentPathname = browserHistory.getCurrentLocation().pathname;
if( currentPathname === "/" || currentPathname === "/signin"){
browserHistory.push('/');
}
const { email } = user;
store.dispatch(logUser(email));
}
else {
browserHistory.replace('/signin');
}
})
I know that it's not pretty solution but it works and it was only home project which was created to learn react. (btw this project is using old react router 3.0 so probalby now using browserHistory is deprecated)
Check that firebase does not interfares with the client side routes :P
You can use Index routes to achieve this.
You have your navigation i.e the layout of all pages in your app component so make it the root route.
Then you want your home route to be your default route so make it your Index route.
You need to import IndexRoute from react-router package (from which you import Route).
Add this-
import { Router, Route, IndexRoute } from 'react-router';
and then make your routes like below.
Use this-
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/home" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')
it's a Server-side vs Client-side issue
check the following thread, it might give you some insights.. React-router urls don't work when refreshing or writting manually
Below example you can refer for :
React Router Navigation
Browser Refresh Issue.
Browser Back Button Issue.
Please make sure you have installed react-router-dom
If not installed. Use this command to install npm i react-router-dom
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Page1 from "./Page1";
import Page2 from "./Page2";
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Page1} />
<Route path="/page2" component={Page2} />
</Switch>
</BrowserRouter>,
rootElement
);
Page1.js
import React from "react";
import {Link } from "react-router-dom";
function Page1() {
return (
<div>
<p>
This is the first page.
<br />
Click on the button below.
</p>
<Link to="/page2"><button>
Go to Page 2
</button>
</Link>
</div>
);
}
export default Page1;
Page2.js
import React from "react";
function Page2() {
return (
<div>
<p>This is the second page.</p>
</div>
);
}
export default Page2;
Add into your webpack.config.js this option
devServer: {
historyApiFallback: true
},
Route tag returns the first matching component.
I think you have interchanged the paths of home and app component.
try this.
<Provider store={store}>
<Router path="/" history={browserHistory}>
<Route path="/" component={App}>
<Route path="/home" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')

Can't make React-Router render two different components, always render root

I have these two components that are completely independent of each other. I want to render App when I enter / and render About when I go to /#/about
I got this piece of code (but I tested quite a few others):
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router'
import App from './App';
import About from './About';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App} >
<Route path="/about" component={About} />
</Route>
</Router>
, document.getElementById('root')
);
I also tried something like
<Route path="/about" component={About} />
<Route path="/" component={App} />
And changed /about to /#/about, about
But it always render the "fallback" /, it always goes to this route, no matter what.
How can I make this app navigate properly to / and /about and render the App and the About components?
#edit
Assuming that my About component is broken, I removed the first Route and kept only the /about (kept only the /about Route) :
<Route path="/about" component={App} />
(I tried keeping About as well in a previous test) and also changed the /about to about and /#/about.
And I get this error on console:
"VM3651 bundle.js:30801 Warning: [react-router] Location "/#/about" did not match any routes"
#edit 2
I made a change, following the example #Dominic posted. I had to make some modifications to make sure both components would render. I added the {this.props.children} to all Components to understand what would happen.
//imports
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={About} >
<IndexRoute component={App} />
<Route path="/about" component={Other} />
</Route>
</Router>
,document.getElementById('root'));
The route http://localhost:3000/#/about is rendering:
> About > App
So it is rendering the IndexRoute, it is not getting caught by the /about.
And this is now exactly what I need, because I didn't want a root component, I wanted 2 routes to 2 different and isolated components. I need something like two sibling routes.
#edit
The About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
<div>
About page
{this.props.children}
</div>
);
}
}
export default About;
Solution:
Since I'm using a HASH (#) in the URL, I should use hashHistory from React Router in the <Router history={hashHistory}>
You're confusing how routes work - About is a child of the App route, so in order to render About, it has to render App.
In other words your App component is the "shell" and all components under it render INSIDE it (via props.children).
You should add another route to render /.
import { ..., IndexRoute } from 'react-router'
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="about" component={About} />
</Route>
Your App does not contain route specific content, it would be something more like this:
<div id="app">
<nav>app navigation</nav>
<main class="route-content">{props.children}</main>
</div>
Docs: https://github.com/ReactTraining/react-router/blob/master/docs/guides/RouteConfiguration.md#adding-an-index
Those routes look correct to me. Are you getting any errors in the console? Maybe your About component is undefined and thus not rendering. Can you post your About component?

Categories

Resources