Blank display when I use link Routes in React - javascript

If I search "http://localhost:3000/" or "http://localhost:3000/login", my display is completely blank.
app.js
import React from 'react'
import Login from './pages/login'
import Home from './pages/home'
import Error from './pages/error'
import { Link, Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Error />} />
</Routes>
)
}
export default App;
home.js
import React from "react";
const Home = () => {
return <h1>The Home</h1>;
};
export default Home;

Refactor to look like:
import { Route, Routes, BrowserRouter } from 'react-router-dom';
// ...
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Error />} />
</Routes>
</BrowserRouter>
);
};

Related

React routing based on id

I work with react-router v6. I want to create a new route based on an id. On my homepage "example.com" I have a selection of articles. I want to create a detail view for each article "example.com/{id}". My approach looks like this:
App.tsx
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
import ProjectWrapper from "./components/ProjectWrapper";
import Home from "./pages/Home";
import PageError from "./pages/PageError";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} >
<Route path=":id" element={<ProjectWrapper />} />
</Route>
<Route path="*" element={<PageError />} />
</Routes>
</BrowserRouter>
);
}
ProjectWrapper.tsx
import { useParams } from "react-router-dom";
import { ProjectList } from "../pages/algorithms/ProjectList";
import PageError from "../pages/PageError";
function ProjectWrapper() {
const { id } = useParams();
const project = ProjectList.find((project) => project.id.toLowerCase() === id?.toLowerCase());
if (project === undefined) return (<PageError />);
return (
<div>
{project!.shortDescription}
</div>
)
}
export default ProjectWrapper;
Am I missing something ?
With the given routing code:
<Routes>
<Route path="/" element={<Home />} >
<Route path=":id" element={<ProjectWrapper />} />
</Route>
<Route path="*" element={<PageError />} />
</Routes>
Home is what is called a Layout Route. Layout routes render some common logic and UI, and an Outlet component for nested Routes to render their content when matched.
Example:
import { ..., Outlet } from 'react-router-dom';
const Home = () => {
...
return (
<>
...
<Outlet /> // <-- nested routes render content here
</>
);
};
If you don't want the Home component to render along with children routes then place it on its own route.
Examples:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/:id" element={<ProjectWrapper />} />
<Route path="*" element={<PageError />} />
</Routes>
or
<Routes>
<Route path="/">
<Route index element={<Home />} />
<Route path=":id" element={<ProjectWrapper />} />
</Route>
<Route path="*" element={<PageError />} />
</Routes>

Matched leaf route at location "/cadastro" does not have an element. This means it will render an <Outlet /> with a null value by default resulting

I've been trying to solve this for a few hours now, everything I do returns this same error.
Matched leaf route at location "/cadastro" does not have an element. This means it will render an with a null value by default resulting in an "empty" page.
routes.js file
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import App from './App';
import Cadastro from "./pages/cadastro";
import CadastroGuiasTuristicos from "./pages/cadastro-guia-turistico";
import DetalhesGuiasTuristicos from "./pages/detalhes-guias-turistico";
import GuiasTuristicos from "./pages/guias-turisticos";
import Home from "./pages/home";
import Login from "./pages/login";
import PlanoEstabelecimentos from "./pages/plano-de-assinatura/estabelecimentos";
import PlanoGuias from "./pages/plano-de-assinatura/guias-turisticos";
const RoutesTeste = () => {
return(
<BrowserRouter>
<Routes>
<Route path="/" component={ <Home/> }></Route>
<Route path="/cadastro" component={ <Cadastro/> }></Route>
<Route path="/cadastro-guia-turisticos" component={ <CadastroGuiasTuristicos/> }></Route>
<Route path="/detalhes-guias-turisticos" component={ <DetalhesGuiasTuristicos/> }></Route>
<Route path="/guias-turisticos" component={ <GuiasTuristicos/> }></Route>
<Route path="/login" component={ <Login/> }></Route>
<Route path="/estabelecimentos" component={ <PlanoEstabelecimentos/> }></Route>
<Route path="/guias-turisticos" component={ <PlanoGuias/> }></Route>
</Routes>
</BrowserRouter>
)
}
export default RoutesTeste;
App.js
import RoutesTeste from './routes';
export default function App() {
return (
<RoutesTeste/>
);
}
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
In Route ,change component to element.
Instead of -
<Route path="/" component={ }>
<Route path="/cadastro" component={ }>
do this-
<Route path="/" element={ }>
<Route path="/cadastro" element={ }>
for all the Route.
Replace the component with element as follows;
<Route path="/" element={ <Home/> }></Route>
It will work...

React Router Route does return anything

I am very beginner in React and while I was practicing Router, I found that does not return the related component.
below is the code.
p.s. BrowserRouter works properly is the Hello world has been rendered.
import React, {Component} from 'react';
import {Route, BrowserRouter} from 'react-router-dom';
import './App.css';
import MainPage from './MainPage';
import About from './About';
class App extends Component {
render(){
return (
<BrowserRouter>
<div> Hello world</div>
<Route exact path="/" component={MainPage}/>
<Route path="about" component={About}/>
</BrowserRouter>
);
}
}
export default App;
For react router dom 6 it should be element:
import { render } from "react-dom";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
// import your route components too
render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
</Route>
</Routes>
</BrowserRouter>,
document.getElementById("root")
);
Sources: https://reactrouter.com/docs/en/v6/getting-started/overview
if you use react-router-dom^6
import {Route, BrowserRouter, Routes} from 'react-router-dom';
<BrowserRouter>
<div> Hello world</div>
<Routes>
<Route exact path="/" element={<MainPage />} />
<Route exact path="/about" element={<About />} />
</Routes>
</BrowserRouter>
or you use react-router-dom^5
import {Route, BrowserRouter, Switch} from 'react-router-dom';
<BrowserRouter>
<div> Hello world</div>
<Switch>
<Route exact path="/" component={MainPage}/>
<Route path="/about" component={About}/>
</Switch>
</BrowserRouter>
You need to wrap Route with Routes or Switch(depending on which version of react-router-dom are you using)
import React, {Component} from 'react';
import {Route, BrowserRouter} from 'react-router-dom';
import './App.css';
import MainPage from './MainPage';
import About from './About';
class App extends Component {
render(){
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={MainPage}/>
<Route path="/about" component={About}/>
</Switch>
</BrowserRouter>
);
}
}
export default App;
Make sure to import it as well!
add / before about route and add Switch or Routes (according to the installed version) to it
Configuring React Router
import React, {Component} from 'react';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import './App.css';
import MainPage from './MainPage';
import About from './About';
class App extends Component {
render(){
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={MainPage}/>
<Route path="/about" component={About}/>
<Switch>
</BrowserRouter>
);
}
}
export default App;
I recommend that you append component after def. of the last Route.
like this...
<Route path="about" component={About}/>
<Outlet/>

How can I redirect in React Router v6?

I am trying to upgrade to React Router v6 (react-router-dom 6.0.1).
Here is my updated code:
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route render={() => <Navigate to="/" />} />
</Routes>
</BrowserRouter>
The last Route is redirecting the rest of paths to /.
However, I got an error
TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.   Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.
However, based on the documentation, it does have render for Route. How can I use it correctly?
I think you should use the no match route approach.
Check this in the documentation: Adding a "No Match" Route
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route
path="*"
element={<Navigate to="/" replace />}
/>
</Routes>
</BrowserRouter>
To keep the history clean, you should set replace prop. This will avoid extra redirects after the user click back.
I found another way to do this:
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
useEffect(() => {
if (LoggedIn){
return navigate("/");
}
},[LoggedIn]);
See Overview, Navigation.
Create the file RequireAuth.tsx
import { useLocation, Navigate } from "react-router-dom";
import { useAuth } from "../hooks/Auth";
export function RequireAuth({ children }: { children: JSX.Element }) {
let { user } = useAuth();
let location = useLocation();
if (!user) {
return <Navigate to="/" state={{ from: location }} replace />;
} else {
return children;
}
}
Import the component to need user a private router:
import { Routes as Switch, Route } from "react-router-dom";
import { RequireAuth } from "./RequireAuth";
import { SignIn } from "../pages/SignIn";
import { Dashboard } from "../pages/Dashboard";
export function Routes() {
return (
<Switch>
<Route path="/" element={<SignIn />} />
<Route
path="/dashboard"
element={
<RequireAuth>
<Dashboard />
</RequireAuth>
}
/>
</Switch>
);
}
In version 5 of React, i.e., react-router-dom, we had the Redirect component. But in version 6 of React it is updated to the Navigate components.
We can pass replace in these components to avoid unnecessary redirects on clicking back and forward option.
Demonstration for usage is attached below:
<Route path="/" element={user ? <Home /> : <Register />} />
<Route path="/login" element={user ? <Navigate to="/" replace /> : <Login />} />
<Route path = "/register" element={user ? <Navigate to="/" replace /> : <Register />} />
FOR react-router VERSION 6
New example after editing----->(more simple easy to read)
import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Home from '../NavbarCompo/About';
import Contact from '../NavbarCompo/Contact';
import About from '../NavbarCompo/About';
import Login from '../NavbarCompo/Login';
import Navbar from '../Navbar/Navbar';
import Error from '../pages/error';
import Products from '../pages/products';
import Data from '../NavbarCompo/Data';
const Roter=()=>{
return (
<Router>
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/contact' element={<Contact />} />
<Route path='/login' element={<Login />} />
<Route path='/product/:id' element={<Products />} />
<Route path='/data' element={<Data />} />
<Route path ='*' element={<Error />} />
</Routes>
</Router>
)
}
export default Roter;
Look at the example
import React from "react";
import Form from "./compo/form";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider, Route,Routes,Navigate } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <Form />
},
{
path: "/about",
element: <h1>hola amigo,you are in about section</h1>
},
{
path:"*",
element:<Navigate to="/" replace />
}
]);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
);
check this out
https://reactrouter.com/en/main/start/overview
<BrowserRouter>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<About />} />
<Route index element={<Navigate to="/home" replace />} />
</Routes>
</BrowserRouter>
import { useNavigate } from "react-router-dom";
import { Button } from "#mui/material";
const component =()=>{
const navigate = useNavigate();
const handelGoToLogin = () => {
navigate('/auth/login')
}
return(<>
//.........
<Button onClick={handelGoToLogin} variant="outlined" color="primary" size="large" fullWidth>
Back
</Button>
</>)
}
import { useState } from "react"
import { Navigate } from "react-router-dom"
const [login, setLogin] = useState(true)
return (<>
{!login && <Navigate to="/login" />}
<>)
For class components, at the first you should make a functional component, and then use HOC technical to use useNavigate React hook.
Like this:
File withrouter.js
import {useNavigate} from 'react-router-dom';
export const withRouter = WrappedComponent => props => {
return (<WrappedComponent {...props} navigate={useNavigate()}/>);
};
Then use it in other class components like this:
export default withRouter(Signin);
And use props for redirect like this:
this.props.navigate('/');

How to set a basename for react-router Router

How can I config the basename, or keep a path in url like localhost:8000/app and when I have to redirect to another Route the Router identify this /app as part of url and do not change it, this is my component structure.
import React from 'react';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
<Router history={browserHistory} >
<Route component={App}>
<Route path="/" component={Home} />
<Route path="/login" component={LoginContainer} />
<Route path="apresentacao">
<IndexRoute component={NameContainer} />
<Route path="2" component={HsContainer} />
<Route path="3" component={McContainer} />
<Route path="4" component={MpvContainer} />
</Route>
</Route>
</Router>
If you are using React Router v4, you can use the basename prop of the Router component to change the base of your app.
import React from "react";
import { Router, Route, browserHistory, IndexRoute } from "react-router";
class App extends React.Component {
render() {
return (
<Router history={browserHistory} basename="/app">
<Route component={App}>
<Route path="/" component={Home} />
<Route path="/login" component={LoginContainer} />
<Route path="apresentacao">
<IndexRoute component={NameContainer} />
<Route path="2" component={HsContainer} />
<Route path="3" component={McContainer} />
<Route path="4" component={MpvContainer} />
</Route>
</Route>
</Router>
);
}
}
If you are using React Router v3, you need to install the history package separately and use the useBasename function.
import React from "react";
import { Router, Route, browserHistory, IndexRoute } from "react-router";
import { useBasename } from 'history'
class App extends React.Component {
render() {
return (
<Router history={useBasename(() => browserHistory)({ basename: '/app' })}>
<Route component={App}>
<Route path="/" component={Home} />
<Route path="/login" component={LoginContainer} />
<Route path="apresentacao">
<IndexRoute component={NameContainer} />
<Route path="2" component={HsContainer} />
<Route path="3" component={McContainer} />
<Route path="4" component={MpvContainer} />
</Route>
</Route>
</Router>
);
}
}

Categories

Resources