routing in react issues - javascript

i am trying to create a basic web page in react which has some <h1> text and two links - one to login page and other to register page. here is the code->
index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js
import './App.css';
import Header from './components/register/header';
import RegistrationForm from './components/register/registrationForm'
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
function App() {
return (
<div className="App">
<br></br>
<h1>Welcome to my website!</h1>
<br></br>
<br></br>
<br></br>
<Link to="/register">Register</Link>
<Route exact path="/register" component={RegistrationForm} />
</div>
);
}
export default App;
what i want is when i click on register button, i want the Header and RegistrationForm component to load and App component to disappear.
This code is not working. i get an empty screen.
if i remove these lines
<Link to="/register">Register</Link>
<Route exact path="/register" component={RegistrationForm} />
the App component works fine. can someone help?
---EDIT---
App.js
import "./App.css";
import Header from "./components/register/header";
import RegistrationForm from "./components/register/registrationForm";
import Home from "./components/home/home";
import { Routes, Route, Link } from "react-router-dom";
function App() {
return (
<div className="App">
<Home />
<Link to="/register">Register</Link>
<Routes>
<Route
path="/register"
element={
<>
<Header />
<RegistrationForm />
</>
}
/>
</Routes>
</div>
);
}
export default App;
Home.js
import React from "react";
function Home() {
return (
<div>
<br></br>
<h1>Welcome to my website!</h1>
<br></br>
<br></br>
<br></br>
</div>
);
}
export default Home;
//end

Router, Switch and Header are missing.
You need something like this :
import { BrowserRouter as Router } from 'react-router-dom';
render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
<div className="App">
<Switch>
<Route exact path="/">
<Home/>
</Route>
<Route exact path="/register">
<Header />
<RegistrationForm/>
</Route>
</Switch>
</div>
<div className="Home">
<br />
<h1>Welcome to my website!</h1>
<br />
<br />
<br />
<Link to="/register">Register</Link>
</div>
I think you will need to make a second Switch like this to share your header between pages except Home :
<div className="App">
<Switch>
<Route exact path="/">
<Home/>
</Route>
<Route path="/">
<Header />
<Switch>
<Route exact path="/register">
<RegistrationForm/>
</Route>
{/* Other routes with the Header */}
</Switch>
</Route>
</Switch>
</div>

App.js
import "./App.css";
import Header from "./components/register/header";
import RegistrationForm from "./components/register/registrationForm";
import Home from "./components/home/home";
import { Routes, Route, Link } from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route exact path="/" element={<Home />} />
<Route
path="/register"
element={
<>
<Header />
<RegistrationForm />
</>
}
/>
</Routes>
</div>
);
}
export default App;

you should wrap the app with Router :
import { BrowserRouter as Router } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
and in App.js you are missing Routes wrapping Route:
import { Routes, Route, Link } from 'react-router-dom';
function App {
*other code*
<Routes>
<Route path="/" component={Home} />
<Route path="/register" component={RegistrationForm} />
</Routes>
}

Related

React Routes fail to route to different paths

I tried to lead from the home page to "/allUsers" page. The homepage has a link that directs to the all Users page. But when I click from the home page to all User page it does not show any content. The link to all Users is "http://localhost:3000/allUsers"
App.js:
import './App.css';
import { Routes, Route } from "react-router-dom";
import { BrowserRouter } from 'react-router-dom';
import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import Home from './components/Home';
import allUsers from './pages/allUsers/allUsers';
import airportEmployee from './pages/AirportEmployee/airportEmployee';
import airlineEmployee from './pages/AirlineEmployee/airlineEmployee';
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/allUsers" element={<allUsers />} />
<Route path="/airline-employee" element={<airlineEmployee />} />
<Route path="/airport-employee" element={<airportEmployee />} />
</Routes>
</div>
);
}
export default App;
Here is the Home.js file
const Home = () => {
return (
<Breadcrumbs aria-label="breadcrumb">
<Link
underline="hover"
color="inherit"
href="/allUsers"
fontSize="large"
>
All Users
</Link>
<Link
underline="hover"
color="inherit"
href="/airport-employee"
fontSize="large"
>
Airport Employee
</Link>
<Link
underline="hover"
color="inherit"
href="/airline-employee"
fontSize="large"
>
Airline Employee
</Link>
</Breadcrumbs>
);
};
export default Home;
Change this in app.js:
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/allUsers" element={<allUsers />} />
<Route path="/airline-employee" element={<airlineEmployee />} />
<Route path="/airport-employee" element={<airportEmployee />} />
</Routes>
</Router>
</div>
);
}
Change in Home.js:
import App from "components/App";
import {Link} from "react-router-dom";
<Link to="/allUsers">All Users</Link>
I think route has a 'exact' keyword to match exactly the url you want.
<Route path="/allUsers" exact element={<allUsers/>} />

Route Error- A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>

I am getting the below error. I have installed npm install react-router-dom on the command prompt. Here is my code for app.js and index.js
Error:
A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .
Please let me know what additionally I have to add to make the code work
**App.Js**
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const Home = () => {
return (
<div>
<p>Home</p>
</div>
);
};
const About = () => {
return (
<div>
<p>About</p>
</div>
);
};
const Contact = () => {
return (
<div>
<p>Contact</p>
</div>
);
};
class App extends Component {
render() {
return (
<Router>
<div>
<h1>W3Adda - Simple SPA</h1>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Users</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
What is the error when you wrap your Route with a Routes?
<Routes>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Routes>
Try this; (change component to element)
import { BrowserRouter as Router, Routes, Route } from "react-router-
dom";
function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path="/user" element={<CreateUser/>}/>
</Routes>
</Router>
);}

React Routing V6 problem, redirecting to another path: '/contact' the content from <Contact /> get updated above nav instead of separate page

I am trying to make Airbnb Clone using React 18, but above nav something like this is happening:
I am using React BrowserRouter V6, whenever we redirect to another page like localhost:3000/about, the about page should open instead of the whole page rendering on all the paths:
App.js:
import './App.css';
import Title from './Components/Title.js'
import Tagline from './Components/Tagline.js'
import Navbar from './Components/Navbar.js'
import Firstpara from './Components/Firstpara.js'
import Card from './Components/Card.js'
import React, { Components } from 'react'
export default function App() {
return (
<div className="App">
<div className="header">
<Title />
<Tagline />
<Navbar />
</div>
<Firstpara />
<Card />
{/* <Contact/> */}
</div>
);
}
Navbar.js:
import React from 'react';
import { Link, BrowserRouter as Router, Route, Routes } from "react-router-dom";
import About from "../Pages/About"
import Contact from "../Pages/Contact"
import Features from "../Pages/Features"
import Error from '../Pages/Error'
export default function Navbar() {
return (
<>
<div className="navbar container-fluid">
<Router>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/features" element={<Features />} />
<Route path="*" element={<Error />} />
</Routes>
<div id="right-menu">
<ul className="navbar-nav">
<li>Visit</li>
<li><Link to="/about">About</Link></li>
<li><Link to="/features">Features</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
</Router>
</div>
</>
)
}
In your app.js file change your code to this (this is just for a demo) you change it as your requirements
import { BrowserRouter,Routes,Route,} from "react-router-dom";
import Navbar from "./components/navbar/Navbar";
import Register from "./components/auth/Register";
import Login from "./components/auth/Login";
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" index element={<Home />} />
<Route path="/login" element={<Login />}/>
<Route path="/register" element={<Login />}/>
<Routes/>
</BrowserRouter>
</>
);
I think the issue you have is that the Navbar is rendering all the routing code, the router, routes, and the links. Then additionally it is rendering the routes above the links.
Move the Router and routes out to the App. The Router should wrap the Navbar and routes, and the routes should be rendered below the Navbar/header.
Example:
App
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
export default function App() {
return (
<Router>
<div className="App">
<div className="header">
<Title />
<Tagline />
<Navbar />
</div>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/features" element={<Features />} />
<Route path="*" element={<Error />} />
</Routes>
<Firstpara />
<Card />
{/* <Contact/> */}
</div>
</Router>
);
}
Navbar
import { Link } from "react-router-dom";
export default function Navbar() {
return (
<div className="navbar container-fluid">
<div id="right-menu">
<ul className="navbar-nav">
<li>Visit</li>
<li><Link to="/about">About</Link></li>
<li><Link to="/features">Features</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
</div>
);
}

React Router v6 : How to render multiple component inside and outside a div with the same path

I'm trying to upgrade to react-router-dom v6 :
v5
In version 5 it works like a charm:
App.js
import Sidebar from "./components/sidebar/Sidebar";
import Topbar from "./components/topbar/Topbar";
import "./app.css";
import Home from "./pages/home/Home";
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import UserList from "./pages/userList/UserList";
import User from "./pages/user/User";
import NewUser from "./pages/newUser/NewUser";
import ProductList from "./pages/productList/ProductList";
import Product from "./pages/product/Product";
import NewProduct from "./pages/newProduct/NewProduct";
import Login from "./pages/login/Login";
function App() {
const admin = JSON.parse(JSON.parse(localStorage.getItem("persist:root"))?.user || "{}")?.currentUser?.isAdmin ;
return (
<Router>
<Switch>
<Route path="/login">
<Login />
</Route>
{admin && (
<>
<Topbar />
<div className="container">
<Sidebar />
<Route exact path="/">
<Home />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/user/:userId">
<User />
</Route>
<Route path="/newUser">
<NewUser />
</Route>
<Route path="/products">
<ProductList />
</Route>
<Route path="/product/:productId">
<Product />
</Route>
<Route path="/newproduct">
<NewProduct />
</Route>
</div>
</>
)}
</Switch>
</Router>
);
}
export default App;
v6
When upgraded to v6 I changed my code to be like this:
<Routes>
<Route path="/login" element={<Login />} />
{admin && (
<>
<Route path="/" element={<Topbar />}/>
<Route path="/" element={
<>
<div className="container">
<Route index element={<Sidebar/>}/>
<Route index element={<Home/>}/>
<Route path="/users" element={<UserList />} />
<Route path="/user/:userId" element={<User />} />
<Route path="/newUser" element={<NewUser />} />
<Route path="/productList" element={<ProductList />} />
<Route path="/product/:productId" element={<Product />} />
<Route path="/newProduct" element={<NewProduct />} />
</div>
</>
}
</>
)}
</Routes>
This is my css file for App.js
Notice: the Topbar component should be outside the div, and react router didn't recognize the components inside the as routes even without div, that means each component should have a unique path, I tried also two components with the same path like this:
<Route path="/" element = {<><Home/><Sidebar/><>}, but the css is not taking effect
.container {
display: flex;
margin-top: 50px;
}
It doesn't work. I tried different code and I searched a lot without finding any solution.
Part of the issue is that you are rendering multiple identical paths, i.e. two "/" paths and two nested index paths. This won't work.
In react-router-dom v6 you can create what are called layout components. The layout components can render your headers and footers, sidebars, drawers, and general content layout elements, and importantly an Outlet component for the nested/wrapped Route components to be rendered into.
Example:
import { Outlet } from 'react-router-dom';
const AppLayout = ({ admin }) => admin ? (
<>
<Topbar />
<div className="container">
<Sidebar />
<Outlet />
</div>
</>
) : null;
Render the layout component into a Route wrapping the routes you want to be rendered into the specific layout.
<Routes>
<Route path="/login" element={<Login/>} />
<Route element={<AppLayout admin={admin} />}>
<Route index element={<Home />} />
<Route path="/users" element={<UserList />} />
<Route path="/user/:userId" element={<User />} />
<Route path="/newUser" element={<NewUser />} />
<Route path="/productList" element={<ProductList />} />
<Route path="/product/:productId" element={<Product />} />
<Route path="/newProduct" element={<NewProduct />} />
</Route>
</Routes>
I will share working code from my project, hope this will help you.
Try to create a component layout that should look something like this:
// Layout.js
import React from "react";
import { NavBar } from "./SidebarNav";
export const Layout = ({ children }) => {
return (
<>
<div className="block">
<NavBar />
<div className="w-full ">{children}</div>
</div>
</>
);
};
and then create routes in a similar way:
// routes.js
import { Routes, Route } from "react-router-dom";
import { Layout } from "./layout/Layout";
import Home from "./pages/Home";
import { ItemList } from "./pages/ItemList";
const BaseRouter = () => (
<>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/item-list/" element={<ItemList />} />
</Routes>
</Layout>
</>
);
export default BaseRouter;
Splitting routes into a separate file gives you more freedom and, above all, makes your code more accessible.
// App.js
import { BrowserRouter as Router } from "react-router-dom";
import BaseRouter from "./routes";
function App() {
return (
<Router>
<BaseRouter />
</Router>
);
}
export default App;

common header issue in react js

I have problem with common header in react js.
Currently login route is displaying common header and i dont want to show on my login page. If i go to contacts page than its showing common header which is perfect
import "./styles/App.scss";
import Navbar from "./components/elements/Navbar";
import Contacts from "./components/contacts/Contacts";
import { Provider } from "react-redux";
import store from "./store";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import AddContact from "./components/contacts/AddContact";
import EditContact from "./components/contacts/EditContact";
import Login from "./components/login/Login";
import Logout from "./components/logout/Logout";
function App(props) {
return (
<Provider store={ store }>
<Router>
<div className="App">
{props.location.pathname !== '/login' ? <Navbar/> : null}
<Route exact path="/login" component={ Login } />
<div className="container">
<div className="py-3">
<Switch>
<Route exact path="/" component={ Contacts } />
<Route exact path="/logout" component={ Logout } />
<Route exact path="/contacts/add" component={ AddContact } />
<Route
exact
path="/contacts/edit/:id"
component={ EditContact }
/>
</Switch>
</div>
</div>
</div>
</Router>
</Provider>
);
}
export default App;
[1]: https://i.stack.imgur.com/7V0qi.png
I think you meant to create Links in NavBar, not declare the Routes:
<Router>
<div className="App">
<div className="container">
<div className="py-3">
<Switch>
<Route exact path="/login" component={Login} />
<Route>
<Navbar />
<Switch>
<PrivateRoute exact path="/" component={Contacts} />
<PrivateRoute exact path="/logout" component={Logout} />
<PrivateRoute exact path="/contacts/add" component={AddContact} />
<PrivateRoute
exact
path="/contacts/edit/:id"
component={EditContact}
/>
</Switch>
</Route>
</Switch>
</div>
</div>
</div>
</Router>
NavBar:
function Navbar() {
const someId = 123 // example
return (
<>
<Link to="/">Login</Link>
<Link to="/logout">Logout</Link>
<Link to="/contacts/add">Add Contacts</Link>
<Link to={`/contacts/edit/${someId}`}>Edit Contact</Link>
</>
)
}
After this, you are most likely to be looking for authentication. I recently wrote an answer on authenticated or protected routes i.e. PrivateRoute.
Also, note that All children of a Switch should be Route or Redirect elements.
You can only show the <Navbar/> when it's not the login page and you need to keep the login page inside the switch for the pages to work.
return (
<Provider store={ store }>
<Router>
<div className="App">
{props.location.pathname !== '/login' ? <Navbar/> : null}
<div className="container">
<div className="py-3">
<Switch>
<Route exact path="/login" component={ Login } />
<Route exact path="/" component={ Contacts } />
<Route exact path="/logout" component={ Logout } />
<Route exact path="/contacts/add" component={ AddContact } />
<Route
exact
path="/contacts/edit/:id"
component={ EditContact }
/>
</Switch>
</div>
</div>
</div>
</Router>
</Provider>
);

Categories

Resources