I came from Angular framework to React and I got confused with router library. I'm trying to create Login page as a separate page in my app which is should contain Navigation and Footer which is part of Main.
I added this code to solve it but run into trouble.
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route} from 'react-router-dom';
import './index.css';
import App from './App';
import Login from './containers/Login';
ReactDOM.render(
<BrowserRouter>
<Route path="/">
<App />
</Route>
<Route path="/login">
<Login />
</Route>
</BrowserRouter>
, document.getElementById('root'));
//app.js
class App extends React.Component {
render() {
return (
<Router>
<div className="App">
<Navbar />
<Switch>
<Route path="/">
<Redirect to="/dashboard" />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
<Route path="/admin">
<Admin />
</Route>
</Switch>
<Footer />
</div>
</Router>
);
}
}
I'm using react-router-dom library.
So the main idea is I desire to load /login page without Navbar and Footer but for other pages in my app like Admin, Dashboard I want them to load with Navbar and Footer (I don't want use conditional rendering here).
But now when I go to /login page I see Navbar and Footer, also I can't go to dashboard.
Please try this.
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import './index.css';
import App from './App';
import Login from './containers/Login';
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/">
<App />
</Route>
</Switch>
</BrowserRouter>
, document.getElementById('root'));
//app.js
class App extends React.Component {
render() {
return (
<Router>
<div className="App">
<Navbar />
<Switch>
<Route path="/dashboard">
<Dashboard />
</Route>
<Route path="/admin">
<Admin />
</Route>
<Route exact path="/">
<Redirect to="/dashboard" />
</Route>
</Switch>
<Footer />
</div>
</Router>
);
}
}
Add the exact property to the route element
In my experience, it is the best practice to place the root path('/') with ëxact props at the later route just before NotFoundPage.
I think it is the same as in Angular router.
Related
Here is my code
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
//import Login from "./components/Login/Login";
import Sidebar from "./components/sidebar/Sidebar.jsx";
import Topbar from "./components/topbar/Topbar.jsx";
import Home from "./Pages/home/Home";
import UserList from "./Pages/userList/UserList";
function App() {
return (
<Router>
<Topbar />
<div className="container">
<Sidebar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/user" element={<UserList />} />
</Routes>
</div>
</Router>
);
}
export default App;
In the above code the Topbar and Sidebar components render but Home and Userlist components do not. What could be wrong?
I want to add the base URL to my react.js project.
However I had tried couple of methods that did not work.
For example, if my project url is :
http://www.myproject.com/
It should appear in address bar as :
http://www.myproject.com/app
http://www.myproject.com/app/home // If home page
http://www.myproject.com/app/about // If about page
Below is my project code.
index.js
import "./index.css"
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider } from './context/AuthProvider';
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import { disableReactDevTools } from '#fvilers/disable-react-devtools';
import App from './App';
if (process.env.NODE_ENV === 'production') {
disableReactDevTools();
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/*" element={<App />} />
</Routes>
</AuthProvider>
</BrowserRouter>
);
App.js
import Layout from './components/authController/Layout'
import Login from './components/authController/Login';
import Home from './components/authController/Home'
import AllUser from './components/authController/AllUser'
import RequireAuth from './components/authController/RequireAuth';
import PersistLogin from './components/authController/PersistLogin';
import Logout from './components/authController/Logout';
import Missing from './Missing';
import {Routes, Route, Navigate} from 'react-router-dom'
function App() {
return (
<div>
<Navbar/>
<Routes>
<Route path="/" element={<Layout />}>
{/* public routes */}
<Route path="login" element={<Login />} />
<Route path="loggedOut" element={<Logout />} />
{/* we want to protect these routes */}
<Route element={<PersistLogin />}>
<Route path="/" element={<Navigate to="/home" replace />} />
<Route path="home" element={<Home/>} />
<Route element={<RequireAuth/>}>
<Route path="alluser" element={<AllUser />} />
</Route>
</Route>
{/* catch all */}
<Route path="*" element={<Missing />} />
</Route>
</Routes>
</div>
);
}
export default App;
What I had tried?
As I referred in stackoverflow and also many other websites, integrated below methods.
Added base url inside package.json file
"homepage": "/app",
Tried to pass the tag <base href="http://myapp.com/app"> within <head> tag in public/index.html page
Passed the base url within BrowserRouter in index.js <BrowserRouter basename="app"> </BrowserRouter>
I am sure I am missing something, it would be great learning if someone help on this or give insights on this.
Thank you
I don't know the correct answer to this , but I believe that you can redirect the route "/" to "/app" . I hope this can help you
Solution:-
Hello everyone.
I got the solution for my query.
I have modified the index.js file like below
<Routes>
<Route path="app/*" element={<App />} />
<Route path="/*" element={<Navigate to="app/home" replace />} />
</Routes>
nothing is rendering on my page and i'm quite confused. I was wondering if anyone could help me with this
App.js:
import React from "react";
import Header from "../layout/Header/Header";
import Footer from "../layout/Footer/Footer.jsx";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
import NotFound from "./NotFound";
import Home from "../pages/Home";
import Pricing from "../pages/Pricing";
import Contact from "../pages/Contact";
import About from "../pages/About";
import Dashboard from "../pages/Dashboard";
import Signin from "../pages/Signin";
class App extends React.component {
render() {
return (
<>
<div className="App">
<Header />
<Router>
<App />
<Switch>
<Route exact path="/home" component={Home} />
<Route exact path="/about" component={About} />
<Route exact path="/contact" component={Contact} />
<Route exact path="/pricing" component={Pricing} />
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/signin" component={Signin} />
<Route component={NotFound} />
<Redirect from="/" to="home" />
</Switch>
</Router>
</div>
<Footer />
</>
);
}
}
export default App;
And here's my index.js:
import React from "react";
import { render } from "react-dom";
import App from "./components/App/App";
//import Signup from "components/pages/SignupBRUH";
import "./styles/styles.scss";
render(<App />, document.getElementById("root"));
My project is also using passport, if that helps with anything. This might be an error with routes or something. I don't know.
Would be awesome if someone could solve this for me, thanks.
Can you try rendering the below for App component, to make sure the template is wired up correctly
class App extends React.component {
render() {
return (
<>
<div>
App Component
</div>
</>
);
}
}
As I am completely new to React I am trying to wrap my App in Router but I get this error I wrapped it in the div but still not working can someone help me Please ?
Sorry if its irrelevant or stupid question.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import routes from'./routes';
import {Router } from 'react-router-dom';
import history from './history';
import App from './App';
ReactDOM.render(
<Router history={history} routes={routes} >
<div>
<App/>
</div>
</Router>, document.getElementById('root'));
When I use 1 route it works but when i put 2 it doesn't the error is here
import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import AddDetails from './components/AddDetails';
import ShowDetails from'./components/ShowDetails';
import NavBar from "./components/NavBar";
class App extends Component {
render() {
return (
<div >
<NavBar/>
<BrowserRouter>
<Switch>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
This should work:
ReactDOM.render((
<Router history={history} routes={routes} >
<App/>
</Router>),
document.getElementById('root')
);
As per your update, you should wrap your Router with a div or you may use switch:
<BrowserRouter>
<div>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</div>
</BrowserRouter>
Add react router Switch to render only one child component
import {BrowserRouter, Route, Switch} from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</div>
</BrowserRouter>
Let me know if the issue still persists
Remove routes prop and pass your routes as child of your div/Switch.
Check the quick start:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/quick-start.md
I created the component NotFound and it works fine when I go to a page that doesn't exist. But the same page it's appearing in all my pages, not only the one that doesn't exist. This is the component:
import React from 'react'
const NotFound = () =>
<div>
<h3>404 page not found</h3>
<p>We are sorry but the page you are looking for does not exist.</p>
</div>
export default NotFound
And this is how I used it in the main page:
class MainSite extends Component {
render () {
return (
<div>
{/* Render nav */}
<Route path='/dashboard' component={Nav} />
<Route path='/retrospectives' component={Nav} />
<Route path='/users' component={Nav} />
<Route path='/projects' component={Nav} />
{/* Dashboard page */}
<ProtectedRoute exact path='/dashboard' component={DashboardPage} />
{/* Retrospectives page */}
<ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} />
{/* Users page */}
<ProtectedRoute exact path='/users' component={UsersPage} />
{/* Projects page */}
<ProtectedRoute exact path='/projects' component={ProjectsPage} />
{/* Retrospective related pages */}
<Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} />
<Route exact path='/join-retrospective' component={JoinRetrospective} />
<ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} />
{/* OnBoarding pages */}
<ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} />
<Route exact path='/auth-handler' component={AuthHandler} />
<Route exact path='/join-organization' component={JoinOrganization} />
</div>
)
}
}
export default MainSite
As you can see I use <Route path="*" component={NotFound} /> to create the 404 pages, but that component is appearing in every existing page as well. How can I fix this?
Try this one:
import { Switch, Route } from 'react-router-dom';
<Switch>
<Route path='/dashboard' component={Nav} />
<Route path='/retrospectives' component={Nav} />
<Route path='/users' component={Nav} />
<Route path='/projects' component={Nav} />
<Route path="" component={NotFound} />
</Switch>
All below example works fine:
<Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path
Or if you want to return a simple 404 message without any component:
<Route component={() => (<div>404 Not found </div>)} />
For those who are looking for an answer using react-router-dom v6, many things had changed. Switch for example doesn't exists anymore, you have to use element instead of component, ... Check this little example to get you an idea:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import './index.css'
import App from './App'
const Test = () => (
<h1>404</h1>
)
ReactDOM.render(
<React.StrictMode>
<Router>
<Routes>
<Route path='/' element={<App />} />
<Route path='*' element={<Test />}/>
</Routes>
</Router>
</React.StrictMode>,
document.getElementById('root')
)
With this you are defining your home route and all the other routes will show 404. Check the official guide for more info.
Try This:
import React from "react";
import { Redirect, Route, Switch, BrowserRouter } from 'react-router-dom';
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
class App extends React.Component {
render(){
return(
<BrowserRouter>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path="*" component={NotFoundPage} />
</Switch>
</BrowserRouter>
)
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Simply import Switch from react-router-dom and wrap all your Routes in the Switch Component. Also Important here is to note to keep your 404Page component at the very bottom(just before your switch ending tag) This way it will match each component with its route first. If it matches, it will render the component or else check the next one. Ultimately if none matching routes will be founded, it will render 404Page
react router is a headache for new coders. Use this code format. This is class component but you can make a functional component and use it.
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
import Footer from './Footer';
class App extends React.Component {
render(){
return(
<Router>
<Routes>
<Route exact path='/' element={HomePage} />
<Route path="*" element={NotFoundPage} />
</Routes>
<Routes>
<Route path="/" element={Footer}/>
</Routes>
</Router>
)
}
}
export default App;