Inside App.js:
import React, { useState } from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Dashboard from './components/Dashboard/Dashboard';
import Preferences from './components/Preferences/Preferences';
import Login from './components/Login/Login';
function App() {
const [token, setToken] = useState();
if(!token) {
return <Login setToken={setToken} />
}
return (
<div className="wrapper">
<h1>Application</h1>
<BrowserRouter>
<Routes>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} /></Route>
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} /></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;`
Inside Dashboard.js (../src/components/Dashboard/Dashboard.js):
import React from 'react';
export default function Dashboard() {
return(
<h2>Dashboard</h2>
);
}
Url: http://localhost:3000/dashboard
I want to see the Dashboard content along with the App page content (Application and Dashboard headers) when I load the browser. But when I load the browser, it only displays the App page content and getting the same error:
"Matched leaf route at location "/dashboard" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page."
You are using Routes instead of Router. Replace it on your line 3 and in the return().
Source: React-router https://v5.reactrouter.com/web/api/Route
//...
import { BrowserRouter, Route, Router } from 'react-router-dom';
//...
return ( ...
<Router>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} />
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} />
</Router>
...)
export default App;
Please specify which version of React router you are using, since a lot of the functionality has changed, is it 6.4 or is still 5 ?
Either way, please remove the comments of the routes, I don't think they help at all.
if you have chosen BrowserRouter from the 6.4 version then it should be used like this
import { BrowserRouter, Route } from 'react-router-dom';
return (
<BrowserRouter>
<Route path="/" element={<RootComp />} >
<Route path="dashboard" element={<Dashboard/>} />
<Route path="preferences" element={<Preferences/>} />
</Route>
</BrowserRouter>
)
export default App;
Where <RootComp /> should have an <Outlet /> as children
import { Outlet } from 'react-router-dom';
const RootComp = () => {
return <div><Outlet /></div>
}
export default RootComp;
Again, this is for the latest React Router component, however, I would advise using createBrowserRouter() rather than the old component-based trees, this way you can programatically create and manage the routes in an Object.
Related
So my div is not showing up on the localhost site from my login.js file. Am I doing something wrong with the routes or something? I don't know why nothing it is not being shown.
login.js file:
import React from 'react';
const Login = () => {
return <div>Login</div>;
};
export default Login;
Here is my app.js file:
import React, { Fragment } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import './App.css';
const App = () => (
<Router>
<Fragment>
<Navbar />
<Routes>
<Route exact path='/' element={<Landing/>} />
</Routes>
<section className="container">
<Routes>
<Route exact path='/Register' element={<Register/>} />
<Route exact path='/Login' element={<Login/>} />
</Routes>
</section>
</Fragment>
</Router>
);
export default App;
Please Help!
It's should work.
I test it and It's working! I don't get any problem.
You can test by do these:
Remove 'exact' from each route. In version of router 6 don't need to write 'exact'.
Write route path in lowercase. // => "/login"
And check your Login component's path properly.
Best of Luck. Happy Coding!
I am using the latest version of react router. When I am using routes in my component, They are not rendering anything but When I remove the routes and use simply the component they are working fine. Not able to understand what is going wrong
This do not work and is not rendering anything on "/" or http://localhost:3000/
import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Route path="/" exact>
<Users />
</Route>
<Navigate to="/" />
</Router>
);
}
export default App;
This is rendering and working fine.
import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return <Users />;
}
export default App;
import React, {useState} from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
import Profiles from "./Profiles" // this is dummy
function App() {
const [state, setState] = useState(false)
return (
<Router>
<Routes>
<Route path="/" element={<Users />}/>
<Route path="/profiles" element={state ? <Profiles /> : <Navigate to="/" />} />
{/* so you redirect only if your state is false */}
</Routes>
</Router>
);
}
export default App;
It is because, You din't provide which element to render in Route. It has to be mentioned like element={<Users />}. So try like below,
import React from "react";
import { BrowserRouter as Router, Route, Routes, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Users />} />
<Navigate to="/" />
</Routes>
</Router>
);
}
export default App;
Based on the docs, all Route components should be placed inside a Routes component, which is nested inside the BrowserRouter.
Also, I noticed you use Navigate everytime, even when you are already at the index path. I think this may cause a problem...
So, with that in mind, Change your code to
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Routes>
<Route path="/">
<Route index element={<Users />} />
</Route>
</Routes>
</Router>
);
}
export default App;
Issue
In react-router-dom#6 the Route component renders its content on the element prop as a ReactNode, a.k.a. JSX, the only valid child of the Route component is another Route component for the case of nesting routes. The Users component should be moved to the element prop.
Also, to render a redirect to a default route, the Navigate component should also be rendered on a generic route.
Solution
Move Users component onto route's element prop.
Move the Navigate component into a generic route and pass the replace prop so issue a redirect.
Example:
function App() {
return (
<Router>
<Route path="/" element={<Users />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Router>
);
}
My route set up returns a blank page with no error, the only thing that's showing up is the side menu. I don't know what I'm doing wrong?
App.js:
import React from "react";
import Sidebar from "./components/Sidebar";
import i18n from './i18n';
import Dash from "./pages/Dash";
import Prof from "./pages/Prof";
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
function App() {
return (
<Router>
<Sidebar/>
<Routes>
<Route path='/' exact component={Dash} />
<Route path='/profile' exact component={Prof} />
</Routes>
</Router>
);
}
export default App;
Dash.js:
import React from "react";
import Dashboard from ".././components/Dashboard";
export default function Dash() {
return (
<>
<Dashboard />
</>
);
}
Prof.js:
import React from "react";
import Dashboard from ".././components/Profile";
export default function Prof() {
return (
<>
<Profile />
</>
);
}
I assume you are using React Router Dom v6 since you are using Routes instead of Switch, in which case it should be element, not component, the propriety where you pass that component for that route. Also, call the component when passing it, like so:
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Sidebar from "./components/Sidebar";
import Dash from "./pages/Dash";
import Prof from "./pages/Prof";
function App() {
return (
<Router>
<Sidebar />
<Routes>
<Route path="/" exact element={<Dash />} />
<Route path="/profile" exact element={<Prof />} />
</Routes>
</Router>
);
}
export default App;
⚠️: notice it's element={<Dash />} and not element={Dash}.
That's not how you use Routes object. You must use Routes > Route as a declaration. In order to go for what your trying which is to render a component based on url, you must use Outlets.
https://reactrouter.com/docs/en/v6/api#outlet
I'm having issues with my project, actually i'm trying to handle a 404 page when the user enters different url outside of the Routes in my App, but using my knowledge of React and react-router only needs to put the last route has no path and exact path wrapped by a Switch from react-router but not work well, the home page is rendering the Home and the NotFound components at same time.
I've tried to remove Container component inside the Router but that makes that all of the components after MenuBar disappears.
I've tried to put path='*' in the last Route having 2 components rendered in the same page.
A picture of what i'm talking about:
2 components at same time
My project have 3 principal files:
1.- Index.js :
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import ApolloProvider from './ApolloProvider';
import 'semantic-ui-css/semantic.min.css';
import 'animate.css/animate.min.css';
import './App.css';
ReactDOM.render(ApolloProvider, document.getElementById('root'));
serviceWorker.unregister();
2.- ApolloProvider.js (using Apollo with GraphQL) :
import React from 'react';
import App from './App';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from '#apollo/react-hooks';
const httpLink = createHttpLink({
uri: 'http://localhost:5000/graphql'
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
export default (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);
3.- And finally App.js :
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Container } from 'semantic-ui-react';
import MenuBar from './Components/MenuBar';
import Home from './Pages/Home';
import Login from './Pages/Login';
import Register from './Pages/Register';
import NotFound from './Pages/404';
const App = props => (
<Router>
<Switch>
<Container>
<MenuBar />
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Container>
</Switch>
</Router>
);
export default App;
I only need to render Home component when the user visits '/' but it's weird how react-router is rendering two components at same time, please le me know if you find where i'm wrong or a solution for that, i'll being posting updates if i find a solution or whatever.
Thanks in advance mates!.
Thanks to #skyboyer and #Hugo Dozois the issue was fixed, this is the updated App.js for future references:
const App = props => (
<Router>
<Container>
<MenuBar />
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Switch>
</Container>
</Router>
);
Best Regards!
I have a react app. It is working fine. It uses redux,react-router 3. The routes work fine, but when I press the back button, they route gets duplicated. For example from localhost:3000/admin/main which I am currently, when I go back, it goes to localhost:3000/admin/admin/main, which return not found.
Here is my routes code:
export default (
<Route path="/" component={App}>
<Route path="home" component={requireNoAuthentication(HomeContainer)} />
<Route path="login" component={requireNoAuthentication(LoginView)} />
<Route exact path="admin/user" component={requireAuthentication(UserView)} />
<Route exact path="admin/main" component={requireAuthentication(UsersListView)} />
<Route path="secure" component={requireAuthentication(CustomerView)} />
<Route exact path="*" component={DetermineAuth(NotFound)} />
</Route>
);
I also get a console error: Adjacent JSX elements must be wrapped in an enclosing tag. If anyone can help it would be great thanks!!
Your HOC wrappers (requireNoAuthentication and requireAuthentication) and using exact (I think this might a react-router v4 only feature?) might be messing with your route history. Try restructuring your routes so that all of them fall under App -- some of the routes fall under RequireAuth, while the rest are public.
As a side note: you can avoid using React.cloneElement with passed down class methods and state by using Redux instead.
routes/index.js
import React from "react";
import { browserHistory, IndexRoute, Router, Route } from "react-router";
import App from "../components/App";
import Home from "../components/Home";
import Info from "../components/Info";
import ShowPlayerRoster from "../components/ShowPlayerRoster";
import ShowPlayerStats from "../components/ShowPlayerStats";
import Schedule from "../components/Schedule";
import Sponsors from "../components/Sponsors";
import RequireAuth from "../components/RequireAuth";
export default () => (
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route component={RequireAuth}>
<IndexRoute component={Home} />
<Route path="roster" component={ShowPlayerRoster} />
<Route path="roster/:id" component={ShowPlayerStats} />
<Route path="schedule" component={Schedule} />
</Route>
<Route path="info" component={Info} />
<Route path="sponsors" component={Sponsors} />
</Route>
</Router>
);
index.js
import React from "react";
import { render } from "react-dom";
import App from "../routes";
import "uikit/dist/css/uikit.min.css";
render(<App />, document.getElementById("root"));
components/App.js
import React, { Component, Fragment } from "react";
import { browserHistory } from "react-router";
import Header from "./Header";
export default class App extends Component {
state = {
isAuthenticated: false
};
isAuthed = () => this.setState({ isAuthenticated: true });
unAuth = () =>
this.setState({ isAuthenticated: false }, () => browserHistory.push("/"));
render = () => (
<Fragment>
<Header
isAuthenticated={this.state.isAuthenticated}
unAuth={this.unAuth}
/>
{React.cloneElement(this.props.children, {
isAuthenticated: this.state.isAuthenticated,
isAuthed: this.isAuthed
})}
</Fragment>
);
}
components/RequireAuth.js
import React, { Fragment } from "react";
import Login from "./Login";
export default ({ children, isAuthenticated, isAuthed }) =>
!isAuthenticated ? (
<Login isAuthed={isAuthed} />
) : (
<Fragment>{children}</Fragment>
);