react-router is not rendering anything - javascript

I created my app with create-react-app and trying to use react-router on it. but it's not working at all.
Here's my Header.js.
import React, { Component } from 'react';
class Header extends Component {
render() {
return (
<nav>
<div className="nav-wrapper blue darken-1">
<a className="brand-logo center">Testing</a>
<div className="right">
<ul>
<li>
<a><i className="material-icons">vpn_key</i></a>
</li>
<li>
<a><i className="material-icons">lock_open</i></a>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
export default Header;
my App.js.
import React, { Component } from 'react';
import Header from './Header';
class App extends Component {
render() {
return (
<div className="App">
<div className="Header">
<Header />
{this.props.children}
</div>
</div>
);
}
};
export default App;
and my index.js here.
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './App';
import Home from './Home';
import Login from './Login';
import Register from './Register';
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Route>
</Router>),
document.getElementById('root')
);
Don't worry about Home, Login, Register thing on index.js. They are super fine.
Am I doing something wrong?

Ho if you're v4* of react-router it won't work that way you should install react-router-dom and import it.
That's the way I did it
import {BrowserRouter, Route} from 'react-router-dom';
//modified code of yours
ReactDOM.render((
<BrowserRouter>
<div>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Route>
</div>
</BrowserRouter>),
document.getElementById('root'));
Note: Don't forget to wrap the route in a wrapper or it'll throw an error!
and to set 404 page just provide another route without any path to it.If no routes found it will be rendered.
<Route component={FourOhFour} /> /* FourOhFour component as 404*/
** Bonus point
If you're new to react-router you may fall in a problem of rendering multiple routes at the same time. But you want to render only one route at a time. at this point.
/*Import Switch also*/
import {BrowserRouter, Route, Switch} from 'react-router-dom';
Then
/*Wrap your route with `Switch` component*/
<BrowserRouter>
<div>
<Switch>
<IndexRoute component={Home}/>
<Route path="/" component={App}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Switch>
</div>
</BrowserRouter>

If you are using React Router 4, as said by other comments, you have to use 'react-router-dom' in order to import it in your component.
import { BrowserRouter as Router } from 'react-router-dom'
you can now give any component as a children of Router (it has to be a single node).
The main difference from the normal RR2-3 is that now every route is a simple component, and you can put it along with other components.
You don't have IndexRoute anymore, you just put the routes in the order you want:
<div>
<Header />
<Route path="/blabla/:bla" component={SingleBlaBla} />
<Route path="/aboutUs" exact component={AboutUs} />
<Route path="/" exact component={Home} />
<Footer />
</div>
there are more than a couple of things to understand, in the options of Route, the use of Switch, Redirect and other very useful components. Try to spend some time on some good documentation since it is a very good version, and it will stick around for a while.
If you can have a look at this wonderful introduction: https://egghead.io/courses/add-routing-to-react-apps-using-react-router-v4
and the doc website: https://reacttraining.com/react-router/

The correct format is
import React from 'react';
import { BrowserRouter as Router, Routes, Route, } from "react-
router-dom";
import './App.css';
import Home from './components/Pages/Home';
function App() {
return (
<>
<Router>
<Routes>
<Route exact path='/' element={<Home/>}/>
</Routes>
</Router>
</>
)}
export default App;

May not be your case but this could help someone else. In my case none of it worked. Turned out to be a case with parcel cache. Delete the parcel cache folder and ran npm run dev again and it worked.

Related

unable to render my components when using with ROUTE in REACTJS

code for app.js .. i have been trying to use ROUTE but unable to render my components
import './App.css';
import Home from './pages/Home';
import Rooms from './pages/Rooms';
import SingleRoom from './pages/SingleRoom';
import Error from './pages/Error';
import { Route, Switch} from 'react-router-dom';
function App() {
return (
<>
<Route exact path="/" component={Home}/>
<Route exact path="/rooms/" component={Rooms}/>
<Route exactpath="/singleroom" component={SingleRoom}/>
</>
);
}
export default App;
You need to wrap your Routes in the Router and Routes components.
This is for react-router-dom v6:
import './App.css';
import Home from './pages/Home';
import Rooms from './pages/Rooms';
import SingleRoom from './pages/SingleRoom';
import Error from './pages/Error';
import { Routes, Route, Switch, BrowserRouter as Router } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/rooms/" element={<Rooms />} />
<Route path="/singleroom" element={<SingleRoom />}/>
</Routes>
</Router>
);
}
export default App;
Assuming you already wrapped your app with <Router> inside your index.js file, now every time you use routes You need to wrap them with <Switch>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/rooms/" component={Rooms}/>
<Route exactpath="/singleroom" component={SingleRoom}/>
</Switch>

ReactJS Route function isn't working for me

I started learning ReactJS yesterday using Academind's crash course for beginners on it. There is a part where he teaches about react-router-dom. I tried using it on App.js and index.js as such:
App.js:
import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import FavouritesPage from "./pages/Favourites";
import NewMeetupsPage from "./pages/NewMeetups";
function App() {
return (
<div>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</div>
);
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import './index.css';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
There shouldn't be any error since I have fixed the syntax and imported the right files given in the video. Yet, in localhost:3000 I get this as the result.
If I just use <AllMeetupsPage /> then it works. If I put it in the route function then it doesn't. How can I fix this?
When you are just using <AllMeetupsPage/> then it's directly rendering that page component in App.js.
It's actually not doing any routing.
To use multiple you also need to wrap it within .
<div>
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/favourites" element={<FavouritesPage />} />
<Route path="/new-meetups" element={<NewMeetupsPage />} />
</Routes>
</div>
You can refer to the following link to get more context of the problem:
[1]: ReactJS: [Home] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
tyr this
import {Routes} from "react-router-dom"
<Routes>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</Routes>

Error "Error: A <Route> is only ever to be used as the child of <Routes> element"

I am trying to use routing for the first time and followed the exact instructions from Udemy:
File App.js:
import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Route path = "/welcome">
<Welcome />
</Route>
<Route path = "/game">
<Game />
</Route>
<Route path = "/leaderboard">
<Leaderboard />
</Route>
</div>
);
}
export default App;
File index.js
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
I get the following error:
Error: A Route is only ever to be used as the child of
element, never rendered directly. Please wrap your Route in a Routes.
Where have I gone wrong?
Yes, in react-router-dom version 6 it is a bit different. Please look as the sample below.
React Router tutorial
import { render } from "react-dom";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import App from "./App";
import Expenses from "./routes/expenses";
import Invoices from "./routes/invoices";
const rootElement = document.getElementById("root");
render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="expenses" element={<Expenses />} />
<Route path="invoices" element={<Invoices />} />
</Routes>
</BrowserRouter>,
rootElement
);
There was a fairly decent change between versions 5 and 6 of react-router-dom. It appears that the Udemy course/tutorial is using version 5 where all you needed was a Router to provide a routing context and Route components just needed to be rendered within this context. In version 6, however, the Route components now need to be rendered within a Routes component (which is an upgrade from the v5 Switch component).
Introducing Routes
One of the most exciting changes in v6 is the powerful new <Routes>
element. This is a pretty significant upgrade from v5's <Switch>
element with some important new features including relative routing
and linking, automatic route ranking, and nested routes and layouts.
The error message is pretty clear, wrap your Route components in a Routes component. The routes also don't take children (other than other Route components in the case of nested routes), they render the components as JSX on the new element prop.
function App() {
return (
<div>
<Routes>
<Route path="/welcome" element={<Welcome />} />
<Route path="/game" element={<Game />} />
<Route path="/leaderboard" element={<Leaderboard />} />
</Routes>
</div>
);
}
The problem is your react-router-dom version.
Probably it's 5.1 or higher.
You can try (in terminal):
npm install react-router-dom#5.3.0
And then your code will be OK. Or you better rebuild your code according to new react-router-dom.
import React from 'react'
import {BrowserRouter, Route, Routes } from 'react-router-dom'
import './App.css';
import Navbar from './components/Navbar';
import { Home } from './components/screens/Home';
import { Login } from './components/screens/Login';
import { Profile } from './components/screens/Profile';
import { Signup } from './components/screens/Signup';
function App() {
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signup />} />
<Route path="/profile" element={<Profile />} />\
</Routes>
</BrowserRouter>
);
}
export default App;
In the latest version of React, 'Switch' is replaced with 'Routes' and 'component' is replaced with 'element'
Enter image description here
Try to wrap your routes by Routes:
import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Routes>
<Route path = "/welcome">
<Welcome />
</Route>
<Route path = "/game">
<Game />
</Route>
<Route path = "/leaderboard">
<Leaderboard />
</Route>
</Routes>
</div>
);
}
export default App;
I think there are many problems that can lead to that issue.
react-router-dom version 6 no longer supports the use of components directly. Use an element to specify the component you route.
Route has to be a child of Routes
Use the simple snippet.
import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import Homescreen from './screens/Homescreen';
function App() {
return (
<div className="App">
<Navbar/>
<BrowserRouter>
<Routes>
<Route path='/home' element={<Homescreen/>} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
The problem right here is that you are using React v5. Since React v6, several changes were included in Router.
So now, to make it work, and as your error message says, you need to wrap your Route element inside a Routes element (Routes now is the equivalent, but an improved version of Switch element). Also, you need to add an "element" prop that accepts JSX instead of wrapping inside the Route element.
So, to make it work, you need to import all these elements like this:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
That being said, your code should look like this:
<Router>
<Routes>
<Route path="/" element={<Welcome/>}>
</Route>
<Route path="/" element={<Game />}>
</Route>
<Route path="/" element={<Leaderboard />}>
</Route>
</Routes>
</Router>
It's probably because you are using version 6 or higher of react-router-dom.
Try:npm i react-router-dom#5.2.0
And it should work.
In the newer version of react-router-dom, we need to nest the Route inside the Routes. Also, component and exact have been removed in newer version.
I was facing same issue and solve it.
Though I am using
react-router-dom#6
So I had to modify app.js and index.js like below
in index.js
import { BrowserRouter } from "react-router-dom";
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
and app.js
import { Routes, Route } from "react-router-dom";
function App() {
return (
<>
<Header />
<main className="py-3">
<Container>
<Routes>
<Route path="/" element={<HomeScreen />} exact/>
</Routes>
</Container>
</main>
<Footer />
</>
);
}
export default App;
according to official documentation
Now, React uses React Router version 6
For React Router version 6, your index.js file is correct:
File index.js:
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
But your App.js file is not correct for React Router version 6, so this is the correct one below:
I changed three parts as shown below:
File App.js
// 1. "Routes" is imported
import { Routes, Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div> // 2. With "<Routes></Routes>", surround "3 <Route /> tags"
<Routes> // 3. Put an element with a component to each "<Route />"
<Route path = "/welcome" element={<Welcome />} />
<Route path = "/game" element={<Game />} />
<Route path = "/leaderboard" element={<Leaderboard />} />
</Routes>
</div>
);
}
export default App;
Use the element option to set your component instead of nesting it into the route tags. Then wrap all the routes with <Routes></Routes>.
Do not forget to add Routes to your imports
import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (
<div>
<Routes>
<Route path = "/welcome" element={<Welcome />}/>
<Route path = "/game" element={<Game />}/>
<Route path = "/leaderboard" element={<Leaderboard />}/>
</Routes>
</div>
);
}
export default App;
Use:
<div>
<Header />
</div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/about" element={<About />} />
</Routes>
I know I'm late but there is another way to do nested routes straight from javascript.
first import
import { useRoutes } from "react-router-dom";
secondly, declare your routes. Here is a quick example
function App() {
return useRoutes([
{
path: "/",
element: <Example/>
},
{
path: "/contact",
element: <Example/>
}]);
}
so now you can have unlimited nested components doing it this way.
in your 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")); //where App must rendered in real DOM?in root
root.render(<App />); //jsx code is a special syntax that browser not undrestand it!
and in your App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupPage from "./pages/NewMeetup";
import FavoritesPage from "./pages/Favorites";
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/new-meetup" element={<NewMeetupPage />} />
<Route path="/favorites" element={<FavoritesPage />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
There is another way to fix the version issues:
App.js File:
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";
function App() {
return (<div>
<BrowserRouter>
<Routes>
<Route path = "/Welcome" element={< Welcome/>}/>
<Route path = "/Game" element={< Game/>}/>
<Route path = "/LeaderBoard" element={< LeaderBoard/>}/>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
Index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

React-router-dom Router not working. Jumps to 404 page only

I am working with react router on a small project. I initially had my AppRouter working with BrowserRouter and everything works fine. But I had to switch to Router so I could add my own history object. With Router my page navigations do not work, instead it jumps straight to my 404 page. Any suggestions on what I am doing wrong will be appreciated.
import React from "react";
import AddExpensePage from "../components/AddExpensePage";
import EditExpensePage from "../components/EditExpensePage";
import ExpenseDashboardPage from "../components/ExpenseDashboard";
import Header from "../components/Header";
import HelpPage from "../components/HelpPage";
import NotFoundPage from "../components/NotFoundPage";
import { createBrowserHistory } from "history";
import LoginPage from "../components/LoginPage";
import { Switch, BrowserRouter, Route, Router } from "react-router-dom";
export const history = createBrowserHistory();
const AppRouter = () => (
<Router history={history}>
<div>
<Header />
<Switch>
<Route path="/" component={LoginPage} exact={true} />
<Route path="/dashboard" component={ExpenseDashboardPage} />
<Route path="/create" component={AddExpensePage} />
<Route path="/edit/:id" component={EditExpensePage} />
<Route path="/help" component={HelpPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</Router>
);
export default AppRouter;
I would suggest that you keep using BrowserRouter. React Hooks now make using history possible despite the type of Router you're using.
From ReactRouter documentation, useHistory is there to your rescue:
The useHistory hook gives you access to the history instance that you may use to navigate.
To access the history object anywhere in your app inside the Routed Components, you can do the following inside of that component:
let history = useHistory();
Then you have access to history.push() and other methods you wish to call to fiddle with history.
Conclusion:
Don't switch to <Router>, keep using <BrowserRouter> and use hooks to access history using useHistory.
You have to wrapp your routes with BrowserRouter component, for example:
const AppRouter = () => (
<Router history={history}>
<div>
<Header />
<BrowserRouter>
<Switch>
<Route path="/" component={LoginPage} exact={true} />
<Route path="/dashboard" component={ExpenseDashboardPage} />
<Route path="/create" component={AddExpensePage} />
<Route path="/edit/:id" component={EditExpensePage} />
<Route path="/help" component={HelpPage} />
<Route component={NotFoundPage} />
</Switch>
</BrowserRouter>
</div>
</Router>
);

React Router v5 nested routes not found

I'm having problems trying to make a simple setup to run. I have used "react-router-dom" because it claims to be the most documented router around.
Unfortunately, the documentation samples are using functions instead of classes and I think a running sample will not explain how routes have changed from previous versions... you need a good sight!. Btw, there are a lot of breaking changes between versions.
I want the following component structure:
Home
Login
Register
Recipes
Ingredients
Have the following components:
index.js (works fine)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
ReactDOM.render((
<BrowserRouter>
<Route component={App}/>
</BrowserRouter>
), document.getElementById('root'));
App.js (fine)
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home'
import Recipes from './recipes/Recipes'
import Ingredients from './ingredients/Ingredients'
class App extends React.Component {
render() {
return (
<div id="App">
<Switch>
<Route exact path='/home' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
</div>
);
}
}
export default YanuqApp;
Ingredients and Recipes components working fine, so I'll skip from here
Home.js - The problem starts here. Home itself loads correctly, but once Login or Register links are clicked, it shows "Not found!" (fallback route in App.js)
import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import Register from './account/register'
import Login from './account/login'
class Home extends React.Component {
render() {
return (
<div>
<div>
This is the home page...<br/>
<Link to='/home/login'>Login</Link><br />
<Link to='/home/register'>Register</Link><br />
</div>
<Switch>
<Route path='/home/login' component={Login} />
<Route path='/home/register' component={Register} />
</Switch>
</div>
);
}
}
export default Home;
Login and register are very similar:
import React from 'react';
class Login extends React.Component {
render() {
alert("login");
return (
<div>Login goes here...</div>
);
}
}
export default Login;
And cannot figure why Login and Register are not found. I have tried also defining routes as:
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
(don't see the gain on using match, as it renders as the expected "/home/register"), but the problem persists in identical way
I think it's because of the exact flag on the Route for home. It does not match the /home exact so it goes to the default not found page.
try to add this in App.js
<Switch>
<Route exact path='/' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
to this is work
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
you should provide match as the props because cont access directly to the match to used it you should provide a match as this following
const namepage=({match})=>{
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
})

Categories

Resources