React router global header - javascript

I just started learning React, I'm trying to make a SPA blog, which has a global positioned fixed header.
import React from 'react';
import { render } from 'react-dom';
// import other components here
render((
<Router history={browserHistory}>
<Route path="/" component={Home} />
<Route path="/About" component={About} />
<Route path="/Contact" component={Contact} />
<Route path="*" component={Error} />
</Router>
), document.getElementById('app'));
So, each routes has the same header and from my angular background, I would use header outside ui-view.
Its a good practice to import the header component in each individual page component, or can I add the header component on my <Router><myHeader/><otherRoutes/></Router>?
Update:
I was thinking to use something like this:
Routes component, where I define my routes:
class Routes extends React.Component {
render() {
return (
<Router history={browserHistory}>
<IndexRoute component={Home} />
<Route path="/studio" component={Studio} />
<Route path="/work" component={Work} />
<Route path="*" component={Home} />
</Router>
)
}
}
And then on main Index.js file I would like to render something like:
import Routes from './components/Routes';
render((
<div>
<div className="header">header</div>
<Routes />
</div>
), document.getElementById('app'));
Can someone explain me? Thanks!

From my experience it can be good to define a layout component for your page, something like...
Layout Component
render() {
return(
<div>
<Header />
{ this.props.children }
/* anything else you want to appear on every page that uses this layout */
<Footer />
</div>
);
}
You then import layout into each of your page components...
Contact Page Component
render() {
return (
<Layout>
<ContactComponent />
/* put all you want on this page within the layout component */
</Layout>
);
}
And you can leave your routing the same, your route will render the contact page and in turn will render your header.
This way you get control of repetitive stuff that will be on multiple pages, if you need one or two slightly different pages you can just create another layout and use that.

I find this way useful:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Header from "./components/Header";
import Home from "./components/Home";
import Dashboard from "./components/Dashboard";
import Footer from "./components/Footer";
class App extends Component {
constructor() {
super();
this.state = {
stuff: stuff;
};
}
render() {
let { stuff } = this.state;
return (
<Router> //wrapper for your router, given alias from BrowserRouter
<div className="App">
<Header /> //this component will always be visible because it is outside of a specific Route
<Route exact path="/" component={Home}/> //at the root path, show this component
<Route path="/dashboard" component={()=><Dashboard stuff={stuff} />}/> //at the path '/dashboard', show this other component
<Footer /> //this is also permanently mounted
</div>
</Router>
);
}
}
export default App;
credit goes to: David Kerr

The question is already answered but I'm here to show another approach and say why I prefer that.
I also think that it's a good thing to have a Layout component
function Layout (props) {
return (
<div>
<Header/>
<div className="content">
{props.children}
</div>
</div>
);
}
But instead of render it into each route component you can render it just once as a parent for your routes.
return (
<Router>
<Layout>
<Switch>
<Route path="/about">
<About/>
</Route>
<Route path="/contact">
<Contact/>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</Layout>
</Router>
);
This is good because in most cases you will not waste time with the layout and if you have different layouts you only need to work inside the Layout component.

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've another solution that is make the routing like this
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>
)
}
and in the header file edit as this
import React, {useLocation} from "react";
const header = () => {
const location = useLocation();
return(
<div className={location.pathname === 'login' ? 'd-none': 'd-block'}>
abc
</div>
)
}
export default header;
this will hide the header panel in login page.

Related

React Router Dom, show Header component only for some pages [duplicate]

This question already has answers here:
How do I render components with different layouts/elements using react-router-dom v6
(2 answers)
Closed 8 months ago.
Header will appear in all components except ConfirmEmail. Basically I don't want the Header to appear when the ConfirmEmail component is opened. What should I do?
Router setup:
import React from 'react';
import {BrowserRouter,Routes ,Route} from 'react-router-dom'
import Header from "../Components/Header";
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import Home from '../Components/Home';
import Contact from '../Components/Contact';
import Login from '../Components/Login';
import Register from '../Components/Register';
import ConfirmEmail from '../Components/SuccessEmailApproved';
const App = () =>{
return(
<BrowserRouter>
<Header/>// If confirmEmail component is opened, hide it here
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/home" element={<Home/>} />
<Route path="/ev" element={<Home/>} />
<Route path="/contact" element={<Contact/>} />
<Route path="/iletisim" element={<Contact/>} />
<Route path="/login" element={<Login/>} />
<Route path="/giris" element={<Login/>} />
<Route path="/register" element={<Register/>} />
<Route path="/kayit" element={<Register/>} />
<Route path="/ConfirmEmail" element={<ConfirmEmail />} /> //I don't want the header component to appear if this is opened. but it will appear in other components.
</Routes>
</BrowserRouter>
);
}
export default App;
Update:
Tried the below solution and it's working, but is there a better way?
{window.location.pathname !== "/ConfirmEmail" ?<Header/>:<></>}
You could create a Layout.js component like below. It's kind of the common way to set up the same structure for multiple pages in React Router Dom v6.
import { Outlet } from "react-router-dom";
import Header from "../Header"; // ⚠️ verify it's the correct path
const Layout = () => {
return (
<>
<Header />
<Outlet />
</>
);
};
export default Layout;
And change App as below. Notice ConfirmEmail page is left out from the pages where you want Header:
// ⚠️ previous imports
import Layout from "./components/Layout"; // ⚠️ verify it's the correct path
const App = () =>{
return(
<BrowserRouter>
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<Home/>} />
<Route path="/home" element={<Home/>} />
<Route path="/ev" element={<Home/>} />
<Route path="/contact" element={<Contact/>} />
<Route path="/iletisim" element={<Contact/>} />
<Route path="/login" element={<Login/>} />
<Route path="/giris" element={<Login/>} />
<Route path="/register" element={<Register/>} />
<Route path="/kayit" element={<Register/>} />
</Route>
<Route path="/ConfirmEmail" element={<ConfirmEmail />} />
</Routes>
</BrowserRouter>
);
}
export default App;
You can have as many layouts as you want (MainLayout, AuthLayout, Layout...). The setup is the same, an Outlet and a Route that has your Layout as element and wraps the pages for that Layout.

Error: [Header] is not a <Route> component

I continue to run into the above mentioned error despite my efforts to fix them. The terminal claims the application compiles without issue but nothing shows up on the browser. I found the error my looking at the console. Here is the index.js file for the Header component that the error is referring to:
import React from "react";
import { Route, Navigate, Router } from "react-router-dom";
import Navigation from "../../components/Navigation";
import About from "../../components/About";
import Portfolio from "../../components/Portfolio";
import Contact from '../../components/Contact';
import Resume from '../../components/Resume';
class Header extends React.Component {
render() {
return (
<Router>
<header>
<Navigation />
</header>
<div className="content">
<Route exact path="/" render={() => <Navigate to="/about" replace={true}/>} />
<Route path="/about" component={About} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={Contact}/>
<Route path="/resume" component={Resume}/>
</div>
</Router>
);
}
}
export default Header;
Here is the App.js:
import React from 'react';
import Header from './components/Header';
import Footer from './components/Footer';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Routes } from 'react-router-dom';
function App() {
return (
<div>
<Routes>
<Header />
<Footer />
</Routes>
</div>
);
}
export default App;
I can provide further code if it is needed.
In react-router-dom version 6 Routes components can have only Route or React.Fragment as a child component, and Route components can have only Routes or another Route component as parent. Header is not a Route component and fails the invariant.
Move the Router into app and render the Header and Footer components into it instead, then wrap the Route components in Routes.
App
function App() {
return (
<div>
<Router>
<Header />
<Footer />
</Router>
</div>
);
}
Header
Fix the Route components, they no longer use component or render to render the routed components, instead they now use an element prop to render ReactElements, i.e. JSX.
class Header extends React.Component {
render() {
return (
<div>
<header>
<Navigation />
</header>
<div className="content">
<Routes>
<Route path="/" element={<Navigate to="/about" replace />} />
<Route path="/about" element={<About />} />
<Route path="/portfolio" element={<Portfolio />} />
<Route path="/contact" element={<Contact />}/>
<Route path="/resume" element={<Resume />}/>
</Routes>
</div>
</div>
);
}
}
Though it may make more sense to move the routes into the app as content between the header and footer.
function App() {
return (
<div>
<Router>
<Header />
<div className="content">
<Routes>
<Route path="/" element={<Navigate to="/about" replace />} />
<Route path="/about" element={<About />} />
<Route path="/portfolio" element={<Portfolio />} />
<Route path="/contact" element={<Contact />}/>
<Route path="/resume" element={<Resume />}/>
</Routes>
</div>
<Footer />
</Router>
</div>
);
}

How do you route within a route in react

I'm new to react and trying to get this whole routing thing down. I have page which I want to render multiple routes withing.
My main index.js file looks like this:
ReactDOM.render(
<BrowserRouter>
<div>
<Switch>
<Route path="/adminDash" exact component={AdminDashMain}/>
<Route path="/admin/ClientSearch" exact component={ClientDetailsMain}/>
<Route path="/" exact component={LogIn}/>
</Switch>
</div>
</BrowserRouter>
, document.getElementById('root'));
in client search main I have 3 components
class ClientDetailMain extends React.Component {
render() {
return(
<div>
<Header />
<SubHeader username={this.props.match.params.username} />
<Display username={this.props.match.params.username}/>
</div>
);
}
}
export default withRouter(ClientDetailMain);
I'm using <Display/> as a container and inside of that I want to have other route so that a person can go to
/admin/ClientSearch/refined
/admin/ClientSearch/general
/admin/ClientSearch/fixed
I figured out that the /admin/ClientSearch will match regardless so the header and subheader show on all 3 routes, however my routes which are written as:
const Display = () =>{
return(
<div>
<Route path ='/admin/ClientSearch/refined' component={<Refined/>
<Route path ='/admin/ClientSearch/general' component={<General/>
<Route path ='/admin/ClientSearch/fixed' component={<Fixed/>
</div>
)
};
export default withRouter(ClientDisplay);
aren't displaying anything. Is this how I should be writing it? When I link to and of those 3 the header and subheader show up but the components in the individuals routes don't.
For example
'/admin/ClientSearch/fixed' shows the header and subheader but none of its own components.
They key is in the "exact" attribute of your Routes. In addition, when you create a component that has routes inside, you can get the url of the previous routes through it's props. Like this example:
class Main extends React.Component {
render(){
return (
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/about' component={About} />
<Route exact path='/contact' component={Contact} />
<Route path='/admin' component={AdminArea} />
</Switch>
)
}
}
Then you have your sub-routes like this:
const AdminArea = ({match}) => (
<Switch>
<Route exact path={`${match.url}/specie`} component={Component} />
<Route exact path={`${match.url}/color`} component={Component} />
<Route exact path={`${match.url}/user/:id`} component={Component}/>
</Switch>
)

404 page in REACT

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;

React-Router only one child

I keep on getting the error:
A 'Router' may have only one child element
when using react-router.
I can't seem to figure out why this is not working, since it's exactly like the code they show in their example: Quick Start
Here is my code:
import React from 'react';
import Editorstore from './Editorstore';
import App from './components/editor/App';
import BaseLayer from './components/baselayer';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {render} from 'react-dom';
const root = document.createElement('div');
root.id = 'app';
document.body.appendChild(root);
const store = new Editorstore();
const stylelist = ['https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.33.1/mapbox-gl.css'];
stylelist.map((link) => {
const a = document.createElement('link');
a.rel = 'stylesheet';
a.href = link;
document.body.appendChild(a);
return null;
});
render((
<Router>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</Router>
), document.querySelector('#app'));
You have to wrap your Route's in a <div>(or a <Switch>).
render((
<Router>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</Router>
), document.querySelector('#app'));
should be
render((
<Router>
<div>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</div>
</Router>
), document.querySelector('#app'));
jsfiddle / webpackbin
This is an API change in react-router 4.x. Recommended approach is to wrap Routes in a Switch: https://github.com/ReactTraining/react-router/issues/4131#issuecomment-274171357
Quoting:
Convert
<Router>
<Route ...>
<Route ...>
</Router>
to
<Router>
<Switch>
<Route ...>
<Route ...>
</Switch>
</Router>
You will, of course, need to add Switch to your imports:
import { Switch, Router, Route } from 'react-router'
I Always use Fragment in react web and native ( >= react 16 )
import React, { Component, Fragment } from 'react'
import { NativeRouter as Routes, Route, Link } from 'react-router-native'
import Navigation from './components/navigation'
import HomeScreen from './screens/home'
import { RecipesScreen } from './screens/recipe'
class Main extends Component {
render() {
return (
<Fragment>
<Navigation />
<Routes>
<Fragment>
<Route exact path="/" component={HomeScreen} />
<Route path="/recipes" component={RecipesScreen} />
</Fragment>
</Routes>
</Fragment>
)
}
}
export default Main
I put all my <Route /> tags inside the <Switch> </Switch> tag like this.
<BrowserRouter>
<Switch>
<Route path='/' component={App} exact={true} />
<Route path='/form-example' component={FormExample} />
</Switch>
</BrowserRouter>
This solves the problem.
If you are nesting other components inside the Router you should do like.
<Router>
<div>
<otherComponent/>
<div>
<Route/>
<Route/>
<Route/>
<Route/>
</div>
</div>
</Router>
If you are using Reach Routers make sure the Code looks like this:
<Router>
<Login path="/" />
<Login path="/login" />
</Router>
Including these Components in a Div in the case of React Routers will make this work but In Reach Routers, Remove that Div Element.
you can also wrap all your route in a parent route which defaults to index page
<Router history={history}>
<Route path="/" component={IndexPage}>
<Route path="to/page" component={MyPage}/>
<Route path="to/page/:pathParam" component={MyPage}/>
</Route>
</Router>
I am using react-router-dom package with version 5.0.1 and it works perfectly fine with your code.
import { BrowserRouter as Router , Router, Link } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
...
class App extends React.Component {
render() {
return (
<Router>
<ul>
<li><Link path='/'>Home</Link></li>
<li><Link path='/about'>About</Link></li>
</ul>
<Route path='/' exact component={Home} />
<Route path='/about' component={About} />
</Router>
);
}
}
export default App;
Not sure if my router might be too simple, or there was a change to this rule but was following along a tutorial that mentioned this limitation (A 'Router' may have only one child element) and it allowed me to add 3 routes without giving any errors. This is the working code:
function render() {
ReactDOM.render(
<BrowserRouter>
<Route exact path="/" component={App} />
<Route path="/add" component={AddAuthorForm} />
<Route path="/test" component={test} />
</BrowserRouter>
,
document.getElementById('root')
);
}
And this are my dependencies:
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
This problem occurs when you don't have parent tag before <Route>inside <Router> so to resolve this problem keep the <Route>enclosed in a parent tag such as <div> , <p> etc.
Example -
<Router>
<p>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</p>
</Router>

Categories