React Router 4 - No Header for Homepage only - javascript

I seem to be facing a simple issue but would like to know the best way to solve it.
I have the following classical router with RR4:
const AppRouter = () => (
<BrowserRouter>
<div className="content">
<Header />
<Switch>
<Route path="/" component={Index} exact={true} />
<Route path="/admin" component={Admin} exact={true} />
<Route path="/account" component={Account} exact={true} />
<Route path="/login" component={Login} exact={true}/>
<Route path="/signup" component={Signup} exact={true}/>
<Route path="/*" component={NotFound} />
</Switch>
<Footer />
</div>
</BrowserRouter>
);
And I would like to have a case on my Index Root where it does not show the header and footer if the user is not connected but still shows these on any other page (whether connected or not) and on Index when connected. Not sure how to manage this probably simple case. Anyone could help ? thanks in advance !

If the connected state is in something like redux you can just have the header and footer read the state and return null. the header can get hold of the current url props with withRouter
import React, { Component } from 'react';
import { withRouter } from 'react-router';
class HeaderComponent extends Component {
const { match, location, history } = this.props
render() {
if(!connected && location.pathname === '/') return null;
return <div>Header</div>
}
}
const Header = withRouter(HeaderComponent)

Related

Why my components don't display on my React page?

So I'm learning React and building an app with multiple pages, I made a Routes file which looks like this:
import 'swiper/swiper.min.css';
import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import Catalog from "../pages/Catalog";
import Detail from "../pages/Detail";
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
component={Catalog}
/>
<Route
path='/:category/:id'
component={Detail}
/>
<Route
path='/:category'
component={Catalog}
/>
<Route
path='/'
exact
component={Home}
/>
</Routes>
);
}
And App.js looks like this:
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Header from './components/header/Header';
import Footer from './components/footer/Footer';
import Router from './config/Router';
function App() {
return (
<BrowserRouter>
<Routes>
<Route render={props =>{
<>
<Header {...props}/>
<Router/>
<Footer/>
</>
}}/>
</Routes>
</BrowserRouter>
);
}
export default App;
As you see, I have a browser router and Route which passes props to a component(as I understood) but for some reason the components don't display on the page(original components just have with their name inside of them, but they don't display in App.js).
And my console also says:
No routes matched location "/"
In routes.jsx file. I'm guessing it should lead to main page, but for some reason the route doesn't match and components in App.js don't display.
In Version 6.0.0 there is not any component prop in Route. It has been changed to element. So you need to change your Router to :
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
element={Catalog}
/>
<Route
path='/:category/:id'
element={Detail}
/>
<Route
path='/:category'
element={Catalog}
/>
<Route
path='/'
exact
element={Home}
/>
</Routes>
);
}
As you've said you're using react-router-dom 6.0.2, and it seems that the tutorial you are following is for the older version (5?). There were some breaking changes in version 6.
You need to change your Router component to use element instead of component:
const Router = () => {
return (
<Routes>
<Route path="/:category/search/:keyword" element={<Catalog />} />
<Route path="/:category/:id" element={<Detail />} />
<Route path="/:category" element={<Catalog />} />
<Route path="/" exact element={<Home />} />
</Routes>
);
};
and also your App component seems to be getting in the way with the nested route.
I think it can be simplified to:
function App() {
return (
<BrowserRouter>
<>
<Header />
<Router />
<Footer />
</>
</BrowserRouter>
);
}
You can see a working demo on stackblitz

Issues in making Routes in Reactjs

I am making a project and getting some problem in managing routes. My Frontend is divided in two parts. One For the Client side and onother is the admin-panel for handling the Client side. For example if I add some Blog from admin-panel then it shows on Client-side. Admin-Panel is for my team to handle the website. Suppose Users will visit on my website at "www.mywebsite.com' and I want that if I enter "www.mywebsite.com/admin" then Admin-panel and Admin-components should open instead of Nav-Components.
How Do I achieve this conditional routing?
Here is the App.js
import React, { Component, useEffect, useState } from "react";
import { Route, Switch } from "react-router-dom";
import Landing from "./components/Landing";
import Home from "./components/Home";
import About from "./components/About";
import Teams from "./components/Team";
import Events from "./components/Events";
import NotFound from "./components/NotFound";
import Blog from "./components/Blog";
import ContactUs from "./components/Contact";
import ComingSoon from "./components/ComingSoon";
import Navbar from "./components/Navbar";
import EventInfo from "./components/EventInfo";
import AdminNavbar from "./admin-panel/AdmiNavbar";
import Login from "./admin-panel/Login";
import Eventadd from "./admin-panel/Eventadd";
import Blogadd from "./admin-panel/Blogadd";
import Dashboard from "./admin-panel/Dashboard";
const NavComponents = () => {
return (
<>
<Switch>
<Route path="/home" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/events" exact component={Events} />
<Route path="/team" exact component={Teams} />
<Route path="/blog" exact component={Blog} />
<Route path="/contact" exact component={ContactUs} />
<Route path="/comingsoon" exact component={ComingSoon} />
<Route path="/eventinfo/:eventName" exact component={EventInfo} />
<Route component={NotFound} />
</Switch>
</>
);
};
const AdminPanel = () =>{
return(
<>
<Switch>
<Route path="/admin/Eventadd" exact component={Eventadd}/>
<Route path="/admin/Blogadd" exact component={Blogadd}/>
<Route path="/admin/DashBoard" exact component={Dashboard}/>
<Route component={NotFound} />
</Switch>
</>
);
};
class App extends Component {
render() {
return (
<>
{window.location.pathname=="/"?"": <Navbar />}
<Switch>
<Route path="/" exact component={Landing} />
<NavComponents />
</Switch>
</>
);
}
}
export default App;
I assume if users enter your website through "www.mywebsite.com/admin" link, you want to re-route them to "/admin/DashBoard" route? The admin dashboard doesn't show because, it only returns the route with EXACT match. It's possible to
A) Add an additional path to handle the routing
<Route path=["/admin/DashBoard", "/admin"] exact component={Dashboard}/>
B) Add a Redirect for admin if you prefer to keep the route as /admin/dashboard
<Redirect exact from="/admin" to={`/admin/dashboard`} />
Edit: (Most importantly)
Also, noticed that you did not include the admin into the main router. You don't need to separate the admin from nav. Suggest to read on the document
https://reactrouter.com/web/api/Switch
Switch renders the first child <Route> or <Redirect> that matches the location.
Overall, it should be combined like this
<Switch>
...user paths
...admin paths
</Switch>

React Router hierarchy with rendering components

I'm passing an object to a class component and want to have that component open in a different route. The routing works, but all the time the props are undefined in the child component unless I move the <Route path=''...> line before every other component. The props work, but the page display is not correct.
PARENT
import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from "./Header";
import DarbaiLT from "./DarbaiLT";
import AnObject from "./AnObject";
let clickeddiv = ''
class App extends Component {
onObjectClick = (clickeddivffromdarbai) => {
clickeddiv = clickeddivffromdarbai;
console.log("clickeddiv: ", clickeddiv);
};
*//clickeddiv is data coming from DarbaiLT component*
};
render() {
return (
<Router>
<div>
<Switch>
<Route path="/object/:id" exact component={AnObject} />
<Route path="/about" exact component={About} />
<Route path="/contacts" exact component={Contacts} />
<Route path="/partners" exact component={Partneriai} />
<DarbaiLT onObjectClick={this.onObjectClick} />
<AnObject dataforComponent={clickeddiv}/> //when this line is the last, it's not working
</Switch>
<Footer />
</div>
</Router>
);
}
}
export default App;
CHILD
import React, { Component } from "react";
class AnObject extends Component {
constructor(props) {
super(props);
}
render() {
return (
<>
<div onClick={() => console.log(this.props.dataforComponent)}>
<img src='../smth/pic.jpg' width="100%" />
</div>
</>
);
}
}
export default AnObject;
if I move the line to the top, passing of props works, but then all pages show only the AnObject, and doesn't render the About, Contacts and so on...
<Router>
<div>
<Header />
<Slides />
<Switch>
<AnObject stateforyou={clickeddiv}/> //if the line is here, routing doesn't work
<Route path="/object/:id" exact component={AnObject} />
<Route path="/about" exact component={About} />
<Route path="/contacts" exact component={Contacts} />
<Route path="/partners" exact component={Partneriai} />
<DarbaiLT onObjectClick={this.onObjectClick} />
</Switch>
<Footer />
</div>
</Router>
the documentation of React Router states that: "All children of a < Switch > should be < Route >".
Using the react-router Switch is like using switch case statement of javascript, whenever the link is matched to the route, the passed component gets rendered. Your problem here, however, is how to pass props to the rendered component which is done this way:
<Switch>
<Route path="/object/:id" exact component={() => <AnObject stateforyou={clickeddiv}/> } />
<Route path="/about" exact component={About} />
<Route path="/contacts" exact component={Contacts} />
<Route path="/partners" exact component={Partneriai} />
</Switch>
I'm not sure I totally understand the issue. But when you use <Switch> in the react-router, it will render only the first match.
You have a switch set up like this:
<Switch>
<Route path="/about" exact component={About} />
<DarbaiLT onObjectClick={this.onObjectClick} />
<AnObject dataforComponent={clickeddiv}/>
</Switch>
This means that if the visitor is at the url /about, it will render only the About component and nothing else. If you want to be able to render multiple components simultaneously as siblings, remove the <Switch>...</Switch>.

How to skip header and footer for certain routes in ReactJS?

I have the following code which renders an app with a header and footer for all pages.
app.js
import React from 'react';
import {
Route,
Switch
} from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'
import Layout from './components/Layout'
import Home from './homeComponent';
import Login from './loginComponent';
import Dashboard from './dashboardComponent';
const App = ({ history }) => {
return (
<Layout>
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/dashboard" component={Dashboard} />
... more routes
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
</Layout>
);
};
export default App;
layout.js
import Header from './headerComponent'
import Footer from './footerComponent'
import React, {Component} from 'react'
class Layout extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
<Footer />
</div>
)
}
}
What is the best way to skip rendering of the header and footer for certain pages like Home and Login routes?
I'd recommend creating two layouts with their own header and footers and a private route:
Public Layout
export const PublicLayout = (props) => <div>
<PublicHeader/>
<Switch>
<Route exact path="/" component={HomePage}/>
<Route exact path='/signin' component={SigninForm} />
<Route exact path='/signup' component={Signup} />
</Switch>
<PublicFooter/>
Protected Layout
export const ProtectedLayout = (props) => <div>
<ProtectedHeader/>
<Switch>
<PrivateRoute exact path='/app/dashboard' component={Dashboard} />
<Route component={NotFound} />
</Switch>
<ProtectedFooter/>
Define high-level routes in app.js:
export default () => {
return <div>
<Switch>
<Route path='/app' component={ProtectedLayout} />
<Route path='/' component={PublicLayout} />
</Switch>
</div>
}
Define PrivateRoute:
export default ({component: Component, ...rest}) => (
<Route {...rest} render={props => (
window.globalState.isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/signin',
state: {from: props.location}
}} />
)
)} />
)
Yeah i know a bit late .
Visual studio 2019
import React from 'react';
import { Container } from 'reactstrap';
import NavMenu from '../components/NavMenu';
export default props => (
<div>
{window.location.pathname !== '/login' ? <NavMenu /> : null}
<Container>
{props.children}
</Container>
</div>
);
i hope somebody helps out there.. !!! Happy coding
I made some solution while solving the problem.
First You can wrap the Switch in a website header and footer
<BrowserRouter>
<WebsiteHeader />
<Switch>
<Route/>
<Route/>
<Route/>
</Switch>
<WebsiteFooter/>
<BrowserRouter>
then inside the header or footer wrap the components using withRouter from 'react-router-dom' so you can access the routes props
const WebsiteHeader = props => {
if (props.location.pathname == "/register") return null;
return (
<Fragment>
<DesktopHeader {...props} />
<MobileHeader {...props} />
</Fragment>
);
};
export default withRouter(WebsiteHeader);
Use render
<ConnectedRouter history={history}>
<Switch>
<Route path="/dashboard" render={props => <Layout><Dashboard {...props} /></Layout>} />
<Route path="/login" component={Login} />
</Switch>
</ConnectedRouter>
For forcefully refresh Header inside routing.
use forceRefresh={true}
const Routing = () => {
return(
<BrowserRouter forceRefresh={true}>
<Header/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/list/:id" component={ListingApi}/>
<Route path="/details/:id" component={HotelDetails}/>
<Route path="/booking/:hotel_name" component={PlaceBooking}/>
<Route path="/viewBooking" component={ViewBooking}/>
<Route exact path="/login" component={LoginComponent}/>
<Route path="/signup" component={RegisterComponent}/>
</Switch>
<Footer/>
</BrowserRouter>
)
}
I would just create a few different layouts one with header and footer and one without. And then instead of wrapping everything into one layout. I'd just do this wrapping inside each page component. So your components would be like:
Dashboard component
<SimpleLayout>
<Dashboard>
</SimpleLayout>
Home component
<MainLayout>
<Home>
</MainLayout>
Try like this
<Route path="/" render={(props) => (props.location.pathname !== "/login") &&
<Header />}>
</Route>
<Route path="/" render={(props) => (props.location.pathname !== "/login") &&
<Menu />}>
</Route>
<PrivateRoute path="/scope" component={Scope} ></PrivateRoute>
<Route exact path="/login" component={Login} />
In this example I'm checking the URL, If the URL is "/Login" I'm removing Menu and header component
For forcefully refresh Header inside routing.
const Routing = () => {
return(
<BrowserRouter forceRefresh={true}>
<Header/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/list/:id" component={ListingApi}/>
<Route path="/details/:id" component={HotelDetails}/>
<Route path="/booking/:hotel_name" component={PlaceBooking}/>
<Route path="/viewBooking" component={ViewBooking}/>
<Route exact path="/login" component={LoginComponent}/>
<Route path="/signup" component={RegisterComponent}/>
</Switch>
<Footer/>
</BrowserRouter>
)
}

Nested <Route> components are not rendering properly in react-redux-router [duplicate]

I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
main.js
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like
<Route path="/home/dashboard" component={Dashboard}
or even better
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}

Categories

Resources