Router is never used, but Routes do not work without importing it - javascript

If I remove Router import from Main.js (I alrady use router in index.js and Router is never used in Main.js) - app pages in Main.js stop showing app at all. Wrapping Routes in another Router does not work either. What should I do?
index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
App.js:
import React from "react";
import Navigation from "./components/Navigation/Navigation.js";
import Main from "./components/Main/Main.js";
const App = () => {
return (
<div className="app">
<Navigation />
<Main />
</div>
);
};
export default App;
Main.js:
import React from "react";
import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";
import Home from "../../pages/Home.js";
import Contacts from "../../pages/Contacts.js";
import About from "../../pages/About.js";
import CardList from "../../components/CardList/CardList.js";
const Main = () => (
<>
<Route exact path="/" component={Home}>
<Redirect to="/products" />
</Route>
<Route path={["/products/:id", "/products"]} component={CardList} />
<Route path="/about" component={About}></Route>
<Route path="/contact" component={Contacts}></Route>
</>
);
export default Main;

first routes should come between switch
const Main = () => (
<>
<Switch>
<Route exact path="/" component={Home}>
<Redirect to="/products" />
</Route>
<Route path={["/products/:id", "/products"]} component={CardList} />
<Route path="/about" component={About}></Route>
<Route path="/contact" component={Contacts}></Route>
<Switch/>
</>
);

Related

While using Route the site is not loading , when i am wrapping inside BroswerRoute only its working

this my App.js Code , not able to find any solution .All item are imported and its working fine if its not wrapped in Route
import React from 'react';
import './App.css';
import { BrowserRouter, Route } from "react-router-dom"
import Home from './Pages/Home';
import SignUpPage from './Pages/SignUpPage';
function App() {
return (
<div className="App">
<BrowserRouter>
<Route >
<Home />`enter code here`
</Route>
<Route path='/signup'>
<SignUpPage />
</Route>
</BrowserRouter>
</div >
);
}
export default App;
You're not wrapping your routes correctly, this is how it should be with react-router-dom v6:
import React from "react";
import './App.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Pages/Home";
import SignUpPage from "./Pages/SignUpPage";
function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/signup" element={<SignUpPage />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
You wrap your routes in a routes component, imported from react-router-dom. You can Then declare your route on one line <Route path="/insertPathHere" element={<YourComponent/>} />

React Project working but not displaying some components

i am trying to build a portfolio website using react and i am using react-router-dom for navigation.
everything was working for a while then i made a stupid mistake of keeping the project in onedrive and had some trouble.
link to code: https://github.com/Raghav-rv28/portfolio-website
Live: https://raghav-rv28.github.io/portfolio-website/, this is not really helpful as we cannot see anything but you can see the screenshots below,
when i run the project on my local machine it runs :
as you can see the elements are there but they just don't appear to me for some reason.
Some of the Code:
import React from 'react'
import {Route, Routes} from 'react-router-dom'
import Layout from './Components/Layout'
import Home from './Components/Home'
import About from './Components/About'
import Contact from './Components/Contact'
import Interests from './Components/Interests'
import Projects from './Components/Projects'
import './App.scss';
function App() {
return (
<>
<Routes>
<Route path="/" element = { <Layout />} >
<Route index element={< Home/>} />
<Route path='About' element={< About/>} />
<Route path='Contact' element={< Contact/>} />
<Route path='Interests' element={< Interests/>} />
<Route path='Projects' element={< Projects/>} />
</Route>
</Routes>
</>
);
}
export default App;
Layout.js:
import React from 'react';
import './index.scss';
import SideNavbar from '../SideNavbar/index';
import { Outlet } from 'react-router-dom';
export default function Layout(){
return(
<div className="App">
<SideNavbar />
<div className="page">
<Outlet />
</div>
</div>)
}
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(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
You nested your routes for (Home, About, Contact, etc.) inside the "Layout" route. This means that react router will render BOTH "Layout" and whichever component is provided by a matching nested route.
Try restructuring your routes like this:
<>
<Routes>
<Route path="/" element = { <Layout />} />
<Route index element={< Home/>} />
<Route path='About' element={< About/>} />
<Route path='Contact' element={< Contact/>} />
<Route path='Interests' element={< Interests/>} />
<Route path='Projects' element={< Projects/>} />
</Routes>
</>
Turns out my stupid As* forgot to import the animation library i'm using and the opacity for the pages was set to 0.

react-router-dom v6 renders a Route when it is supposed to not render it

I want to render private routes for logged in users. For some reason react-router-dom (v6) renders private routes even if PrivateRoute returns null. Also, I couldn't see any console.logs from inside PrivateRoute. Any ideas?
EDIT
It renders Dashboard when you go to localhost/dashboard and Settings when you go to localhost/settings, even though both components are passed to PrivateRoute, which returns null.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
App.js
import {Route, Routes} from 'react-router-dom';
import {Home} from './components/Home';
import {Pricing} from './components/Pricing';
import {Dashboard} from './components/Dashboard';
import {Settings} from './components/Settings';
import {Login} from './components/Login';
import {Header} from './components/Header';
import {PrivateRoute} from './components/PrivateRoute';
const App = () => {
return (
<div>
<Header />
<Routes>
<Route path='/' element={<Home/>} />
<Route path='/pricing' element={<Pricing />} />
<PrivateRoute path='/dashboard' element={<Dashboard />} />
<PrivateRoute path='/settings' element={<Settings />} />
<Route path='/login' element={<Login />} />
</Routes>
</div>
);
};
export default App;
PrivateRoute.js
export const PrivateRoute = ({path, element}) => {
console.log('PrivateRoute'); **// couldn't see this in the console**
return null;
};
Unfortunately, according to the documentation, the new way to do this looks like this:
<Route
path="/protected"
element={
<RequireAuth>
<ProtectedPage />
</RequireAuth>
}
/>
https://reactrouter.com/docs/en/v6/examples/auth
Full code exemple:
https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx

Build independant admin router with react

I've built an app with its specific router. Now I want to improve my app by coding an admin interface. The thing is, I have components (Navbar and Footer) that surround my routes (see code below).
So if I simply create an admin interface and nest it inside my existing router, my app's navbar and footer will appear on the admin pages.
I would like to code my admin interface with its own navbar and components.
Is there a way to do so ?
AppRouter.js:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import LandingPage from '../ui/landing-page/LandingPage';
import App from '../ui/App';
import NotFoundPage from '../ui/NotFoundPage';
import NavBar from '../ui/NavBar';
import Footer from '../ui/Footer';
import FaqPage from '../ui/FaqPage';
import PrivacyPage from'../ui/PrivacyPage';
import LegalNoticePage from '../ui/LegalNoticePage';
const browserHistory = createBrowserHistory();
export const AppRouter = () => (
<Router history={browserHistory}>
<div>
<NavBar />
<Switch>
<Route exact path="/" component={LandingPage}/>
<Route exact path="/meals" component={App}/>
<Route exact path="/faq" component={FaqPage}/>
<Route exact path="/privacy" component={PrivacyPage}/>
<Route exact path="/legal_notice" component={LegalNoticePage}/>
<Route component={NotFoundPage}/>
</Switch>
<Footer />
</div>
</Router>
);
export default AppRouter;
Your <NavBar /> isn't surrounding your <Router>, it's surrounding your routes. Since you can nest Routers, you could have a <Route> which matches all path="/admin" and then within that put the admin-only NavBar.
You can read more about nested routes here.
Here's a code example:
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Switch, Route } from "react-router-dom";
const Admin = ({ match }) => (
<React.Fragment>
<h1>admin bar</h1>
<Route path={`${match.path}/1`} render={() => <h2>one</h2>} />
<Route path={`${match.path}/2`} render={() => <h2>two</h2>} />
</React.Fragment>
);
const Other = ({ match }) => (
<React.Fragment>
<h1>other bar</h1>
<Switch>
<Route path={`${match.path}/2`} render={() => <h2>one</h2>} />
<Route path={`${match.path}/2`} render={() => <h2>two</h2>} />
</Switch>
</React.Fragment>
);
const App = () => (
<BrowserRouter>
<Switch>
<Route path="/admin" component={Admin} />
<Route path="/other" component={Other} />
</Switch>
</BrowserRouter>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
And accompanying CodeSandbox.

Declaring React Routes in a separate file and Importing

I am new to React. I have been trying to declare routes in a file and then use it in another file.
Here is my routes.js
import React from 'react';
import { Route } from 'react-router-dom';
import App from './components/App';
import Template1 from './components/template1';
import Template2 from './components/template2';
import Template3 from './components/template3';
const routes = (
<Route exact path="/" component={App}>
<Route exact path="/sessionstate1" component={Template1} />
<Route exact path="/sessionstate2" component={Template2} />
<Route exact path="/sessionstate3" component={Template3} />
</Route>
)
export default routes
and index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import './styles/css/index.css';
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
I am not getting any errors or warning but the page is not loading. Please tell me what I am missing
Thanks
well i had the same issue a few days ago, and the solution for me was this...
This one of the routes files:
import React from 'react';
import { Route } from 'react-router-dom';
import { ComponentY } from '../components/functionalitys';
export default [
<Route path="/appointment" component={ComponentY} exact key="create" />,
];
This another route file:
import React from 'react';
import { Route } from 'react-router-dom';
import { LoginPage, Register } from '../components/user';
export default [
<Route path="/register" component={Register} exact key="create" />,
<Route path="/login" component={LoginPage} exact strict key="login" />
];
And this is how I imported in the main app.js:
import routesFromFile1 from './the/route';
import routesFromFile2 from './the/other/route';
class App extends Component{
render(){
return(
<div className="wrapper">
<section className="content container-fluid">
<Switch>
<Route exact path="/" component={Home} strict={true} exact={true}/>
<Route path="/500" component={InternalServer} />
{routesFromFile1}
{routesFromFile2}
</Switch>
</section>
</div>
)
}
}
I hope this help Someone! Cheers!!
You don't need to wrap your Routes inside a div. Try something like this:
routes.js
import React from 'react';
import { Router, Route } from 'react-router';
import { Template1, Template2, Template3 } from './templates';
const createRoutes = () => (
<Router>
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Router>
);
export default createRoutes;
index.js
import ReactDOM from 'react-dom';
import createRoutes from './routes';
const routes = createRoutes();
ReactDOM.render(
routes,
document.getElementById('root')
);
index.js:
import LoginRoutes from './login/routes'
let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));
<Router routes={routeConfig}/>
routes.js:
export default (store) => {
return [
{path: '/login', component: Login},
{path: '/signup', component: SignUp},
]
}
This way you can add routes from different files and spread your route definitions to different folders that serve the contextual purpose of the route.
The store variable is there in case you want to use redux and want to have an onEnter event on the route. Example:
export default () => {
const sessionEnter = (location) => {
let {appId} = location.params;
store.dispatch(loadApp(appId));
return [
{path: '/apps/:appId', component: App, onEnter: sessionEnter},
]
}
I find onEnter events a good alternative to componentDidMount, data-fetching-wise. Invoking a data fetch on route level makes more sense to me as I see the component as part of the presentation level.
I think the problem is with wrapping the Route inside a div.
Try wrapping them inside a Route like following. Try this fiddle and change the routes wrapper to div.
const routes=(
<Route >
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Route >
)
export default routes;
And import it into index.js
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
With Typescript
Sepate the file for routes as routes.ts
export const routes = [
{ path: '/', component: Home },
{ path: '/auth-callback', component: authCallback },
{ path: '/fetch-data/:startDateIndex?', component: FetchData }
];
In the App.tsx
export function App() {
const routeComponents = routes.map(({ path, component }, key) => <Route exact path={path} component={component} key={key} />);
return (
<Layout>
{routeComponents}
</Layout>
);
}
Layout.tsx
export default (props: { children?: React.ReactNode }) => (
<React.Fragment>
<div>
<NavMenu />
<TopAppBarFixedAdjust>
{props.children}
</TopAppBarFixedAdjust>
</div>
</React.Fragment>
);
I know I'm little late but here my working
here a working demo
my dependencies are
"react": "16.2.0",
"react-dom": "16.2.0",
"react-router-dom": "4.2.2",
"react-scripts": "1.1.0"
create nav.js file as this
this file is responsible for storing all the links for navbar
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navi extends Component {
render = () => (
<div>
<Link to="/">Go to Home</Link> <br />
<Link to="/about">Go to About</Link> <br />
<Link to="/any-route">404 page</Link>
</div>
);
}
export default Navi;
Then the routes.js file
here you will define all your routes, and your pages where the routes should navigates to
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
// your components
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const MissingPage = () => <h1>404</h1>;
const routes = (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route component={MissingPage} />
</Switch>
);
export default routes;
finally here is the code for index.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Navi from "./nav";
import routes from "./routes";
// initialize rotues and navi links
const initRoutes = () => (
<Router>
<div>
<Navi />
{routes}
</div>
</Router>
);
const initializedRoutes = initRoutes();
ReactDOM.render(
initializedRoutes,
document.getElementById("root")
);
This is the routing page created
routing page imported
Hope, it will help everyone. click the link to see code.!!
In react-router-dom version 6.x.x
Suppose you have the following URLs in your react app
/
/home
/handlers
/handlers/notes
/handlers/users
you can isolate all routing components related to handlers(including its nested URLs) by:
Define your main routing
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/home" element={<HomePage />} />
<Route path="/handlers/*" element={<AllHandlersPages />} />
</Routes>
</BrowserRouter>
Notice the existence of path="/handlers/*" where we have a wildcard * to tell react-router-dom to match with any nested route too
then
declare AllHandlersPages in another file like this
export function AllHandlersPages() {
return (
<Routes>
<Route>
<Route index element={<HandlersIndexPage />} />
<Route path="notes" element={<NotesPage />} />
<Route path="users" element={<UsersPage />} />
</Route>
</Routes>
);
}
Because <Route /> can't be defined unless it has a parent <Routes /> don't forget to make them nested properly.
Full working Demo
Try it like this way
import React from "react";
import {HashRouter as Router, Route} from 'react-router-dom';
import NoteContainer from "./component/note/index.jsx";
import Header from "./component/common/header.jsx";
const App = (props) => {
return (
<div className="container">
<Header/> {props.children}
</div>
);
};
var x = () => {
return (
<h1>Hello world!</h1>
);
};
module.exports = () => {
return (
<Router>
<App>
<Route path="/" component={NoteContainer}/>
<Route path="/inbox" component={x}/>
</App>
</Router>
);
};
I did it with very simple way. Follow the two steps below.
In App.js
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "./component/common/header";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import routes from "./routes";
function App() {
return (
<Router>
<section className="container">
<Header />
{routes}
</section>
</Router>
);
}
export default App;
in routes.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Overview from "./component/overview/overview";
import UsersList from "./component/userslist/UsersList";
import FavUserList from "./component/userslist/FavUserList";
const routes = (
<Switch>
<Route exact path="/" component={Overview} />
<Route path="/adduser" component={UsersList} />
<Route path="/favuser" component={FavUserList} />
</Switch>
);
export default routes;
Note: Make sure you import like this
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
In < Header /> component you have to declare navigation link.
i'm starting into react too, and i figured out a way to make what you are looking for.
What i did was inside the app file (which comes default in every project) i imported the routes file, the routes file is located in a folder called approuter (you can name it whatever you want), i'll write some of my code so you can see what i mean
//APP FILE
import AppRouter from './router/approuter'
function App() {
return (
<>
<div className='app' id="mode">
<AppRouter />
</div>
</>
)
}
export default App
//ROUTER FILE/
import { Route, Routes } from 'react-router-dom'}
import Register from "../pages/register"
import Login from "../pages/login"
export default function AppRouter() {
return (
<>
<div>
<Routes>
<Route path="login" element={<Login />}/>
<Route path="register" element={<Register />}/>
</Routes>
</div>
</>
)
}
This actually worked in a project i'm currently working on, i hope this can answer your question
**index.js**
import ReactDOM from "react-dom/client";
import Paths from "./routes/Paths";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Paths />
</React.StrictMode>
);
**Paths.js**
import LoginSample from "../portal/LoginSample";
import Dashboard from "../portal/Dashboard";
function Paths() {
return (
<Router>
<Routes>
<Route path="/" element={<LoginSample />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
export default Paths;
Also new to react and was running into the same issue. Here is what I tried (obviously different code and structure, but what we're looking for should be the same functionality)
index.js
import React from "react";
import ReactDOM from "react-dom";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import routes from "./routes";
const allRoutes = routes;
ReactDOM.render(
allRoutes,
document.getElementById("app")
)
and the routes.js file.
import React from "react";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import App from "./pages/App";
import Detail from "./pages/Detail";
import List from "./pages/List";
const routes = (
<BrowserRouter>
<div>
<Route exact path="/" component={ App } />
<Route path="/" component={ List } />
<Route path="/detail/:repo" component={ Detail } />
</div>
</BrowserRouter>
);
export default routes;
Let me know if that works for you.

Categories

Resources