React router dom routing to ItemDetail - javascript

I am doing a personal React.js project. I am trying to use react-router-dom, but I haven't been able to make it work. I did the BrowserRouter in the App.js. Till there the app works fine, but I cannot make the routing redirect dynamically to a map item. I tried to follow the documentation and some tutorials unsuccesfully. The data comes from the Star Wars API This is the code:
App.js:
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<Router>
<>
<Navbar />
<Routes>
<Route exact path='/' element={<Home />} />
</Routes>
<Routes>
<Route exact path to='/:movieId' element={<MovieDetail />} />
</Routes>
</>
</Router>
);
}
export default App;
ItemDetail:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
const MovieDetail = () => {
const { movieId } = useParams();
const [result, setResult] = useState([]);
const fetchData = async () => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
setResult(json.result);
}
useEffect(() => {
fetchData();
}, []);
let movieMatch = (result.find(value) => value.properties.title == movieId)
return (
<div>
<h2>
{result
.find((value) => {value.properties.title == movieId})}
</h2>
</div>
);
}
export default MovieDetail;
UPDATE
This is a link to the whole code in codesand with updated App.js

From your code I'm assuming you're using React Router v6 in your project. Try the below code:
import './App.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<BrowserRouter>
<Routes>
<Navbar />
<Route path='/' element={<Home />} />
<Route path=':movieId' element={<MovieDetail />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Checkout React Router's Documentation for more detail.

if you are using index.js as a wrapper for app.js <BrowserRouter /> or <Router /> in your case is not used in app.js it's used in index.js otherwise it will not work
index.js should look like this : -
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
function App() {
return <h1>Hello React Router</h1>;
}
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
**For example just Let's say you are having "/movies" route and you want when ever your app (route = "/") starts / loads up to be redirected to "/movies" **
then wrap the routing logic with *<Switch />* ,make use of Redirect property of router dom to redirect from "/" to "/movies" and use component instead of element to render the corresponding component plus dont wrap with <Routes> </Routes> every time you are doing the route as we used it in index.js
then app.js will be : -
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<>
<Navbar />
<Switch>
<Route exact path='/movies' component={<Home />} />
<Route exact path to='movies/:movieId' component={<MovieDetail />}
// to redirect from "/" to "/movies"
<Redirect from="/" to="/students"></Redirect>
);
}

Related

React-router is not displaying component in the browser

Inside App.js:
import React, { useState } from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Dashboard from './components/Dashboard/Dashboard';
import Preferences from './components/Preferences/Preferences';
import Login from './components/Login/Login';
function App() {
const [token, setToken] = useState();
if(!token) {
return <Login setToken={setToken} />
}
return (
<div className="wrapper">
<h1>Application</h1>
<BrowserRouter>
<Routes>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} /></Route>
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} /></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;`
Inside Dashboard.js (../src/components/Dashboard/Dashboard.js):
import React from 'react';
export default function Dashboard() {
return(
<h2>Dashboard</h2>
);
}
Url: http://localhost:3000/dashboard
I want to see the Dashboard content along with the App page content (Application and Dashboard headers) when I load the browser. But when I load the browser, it only displays the App page content and getting the same error:
"Matched leaf route at location "/dashboard" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page."
You are using Routes instead of Router. Replace it on your line 3 and in the return().
Source: React-router https://v5.reactrouter.com/web/api/Route
//...
import { BrowserRouter, Route, Router } from 'react-router-dom';
//...
return ( ...
<Router>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} />
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} />
</Router>
...)
export default App;
Please specify which version of React router you are using, since a lot of the functionality has changed, is it 6.4 or is still 5 ?
Either way, please remove the comments of the routes, I don't think they help at all.
if you have chosen BrowserRouter from the 6.4 version then it should be used like this
import { BrowserRouter, Route } from 'react-router-dom';
return (
<BrowserRouter>
<Route path="/" element={<RootComp />} >
<Route path="dashboard" element={<Dashboard/>} />
<Route path="preferences" element={<Preferences/>} />
</Route>
</BrowserRouter>
)
export default App;
Where <RootComp /> should have an <Outlet /> as children
import { Outlet } from 'react-router-dom';
const RootComp = () => {
return <div><Outlet /></div>
}
export default RootComp;
Again, this is for the latest React Router component, however, I would advise using createBrowserRouter() rather than the old component-based trees, this way you can programatically create and manage the routes in an Object.

react-router-dom v6 renders only default route

I'm starting a new project using React Router Dom v6 and I'm in trouble with one of the first steps: setting the routes for the App.
I just created two pages: AuthPage and DashboardPage and I would like to be able of rendering both of them if, from the browser, I navigate to:
localhost:PORT/ : should render DashboardPage
localhost:PORT/auth: should render AuthPage
but right no the only page rendered is DashboardPage even if I try to navigate to non-existing routes.
This is my code so far:
main.tsx
import { createRoot } from 'react-dom/client'
import { MemoryRouter as Router } from 'react-router-dom'
import { ThemeProvider } from '#mui/material/styles'
import { theme } from './theme'
import App from './App'
const root = createRoot(document.getElementById('root') as HTMLElement)
root.render(
<ThemeProvider theme={theme}>
<Router>
<App />
</Router>
</ThemeProvider>
)
App.tsx
import { Route, Routes } from 'react-router-dom'
import AuthPage from './pages/AuthPage'
import DashboardPage from './pages/DashboardPage'
import NotFoundPage from './pages/NotFoundPage'
import { routes } from './routes'
function App() {
return (
<Routes>
<Route path={routes.dashboard.url} element={<DashboardPage />} />
<Route path={routes.auth.url} element={<AuthPage />} />
<Route path={routes.notFound.url} element={<NotFoundPage />} />
</Routes>
)
}
export default App
routes.ts
export const routes = {
auth: {
url: '/auth'
},
dashboard: {
url: '/'
},
notFound: {
url: '*'
}
}
Use BrowserRouter instead of MemoryRouter :
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { ThemeProvider } from '#mui/material/styles'
import { theme } from './theme'
import App from './App'
const root = createRoot(document.getElementById('root') as HTMLElement)
root.render(
<ThemeProvider theme={theme}>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
)
As I know, exact option doesn't supported in react-router v6.
Try to use index option.
<Route path="/*">
<Route index element={< DashboardPage />} />
<Route path={routes.auth.url} element={<AuthPage />} />
// ... other routes
</Route>

React Router Dom routes are returning blank pages

My route set up returns a blank page with no error, the only thing that's showing up is the side menu. I don't know what I'm doing wrong?
App.js:
import React from "react";
import Sidebar from "./components/Sidebar";
import i18n from './i18n';
import Dash from "./pages/Dash";
import Prof from "./pages/Prof";
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
function App() {
return (
<Router>
<Sidebar/>
<Routes>
<Route path='/' exact component={Dash} />
<Route path='/profile' exact component={Prof} />
</Routes>
</Router>
);
}
export default App;
Dash.js:
import React from "react";
import Dashboard from ".././components/Dashboard";
export default function Dash() {
return (
<>
<Dashboard />
</>
);
}
Prof.js:
import React from "react";
import Dashboard from ".././components/Profile";
export default function Prof() {
return (
<>
<Profile />
</>
);
}
I assume you are using React Router Dom v6 since you are using Routes instead of Switch, in which case it should be element, not component, the propriety where you pass that component for that route. Also, call the component when passing it, like so:
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Sidebar from "./components/Sidebar";
import Dash from "./pages/Dash";
import Prof from "./pages/Prof";
function App() {
return (
<Router>
<Sidebar />
<Routes>
<Route path="/" exact element={<Dash />} />
<Route path="/profile" exact element={<Prof />} />
</Routes>
</Router>
);
}
export default App;
⚠️: notice it's element={<Dash />} and not element={Dash}.
That's not how you use Routes object. You must use Routes > Route as a declaration. In order to go for what your trying which is to render a component based on url, you must use Outlets.
https://reactrouter.com/docs/en/v6/api#outlet

Why is React Router v6 not rendering my components?

I know this question has been asked a lot and I've looked at quite a lot of answers and articles including one on how to upgrade from React Router V5 to V6 since I'm used to V5. However, V6 is giving me a weird issue which I don't know how to fix or what am I doing wrong.
Here's my code below
App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Login from './components/dashboard/Login';
import Profile from './components/dashboard/Profile';
import './resources/style/tutorApp.css';
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Router>
<Routes>
<Route path="/" element={ <Profile /> } />
<Route path="/Login" element={ <Login /> } />
</Routes>
</Router>
);
}
}
Profile.js
import React, { Component } from 'react';
class Profile extends Component {
render() {
return (
<div>
<h1>This is my Profile Page.</h1>
</div>
);
}
}
export default Profile;
Login.js
import React, { Component } from 'react';
class Login extends Component {
render() {
return (
<div>
<h1>This is my Login page.</h1>
</div>
);
}
}
export default Login;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');
ReactDOM.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>,
rootElement);
registerServiceWorker();
I just get a blank window in the browser. Nothing is rendered!
What is the problem?
You are mounting a router inside another router.
In ReactDom.render you're wrapping your app in BrowserRouter.
import { BrowserRouter } from 'react-router-dom';
// ...
ReactDOM.render(
<BrowserRouter basename={baseUrl}> // <-- this is the outer browser router
<App />
</BrowserRouter>,
rootElement
);
However inside your app you mount another BrowserRouter in your render method.
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
// ...
render () {
return (
<Router> // <-- this is the nested browser router
<Routes>
<Route path="/" element={ <Profile /> } />
<Route path="/Login" element={ <Login /> } />
</Routes>
</Router>
);
}
To fix the problem simply remove one or the other.
The rest of your code looks fine.

React functional components not rendering in App.js

I am using only functional components in React so I can get a better grip on hooks.
But I am having trouble rendering my functional components in the App.js.
Why will only the ‘Login’ component/path render in the browser? None of the others. Please help me discover what is wrong with my App.js. Thank you!
App.js (I have commented out the hook/removed the prop, to simplify it)
import { React, useState } from 'react';
import './App.css';
import { Route } from 'react-router-dom';
import Home from './components/Home'
import Login from './components/Login'
import Signup from './components/Signup';
console.log('app loading')
function App() {
// const [user, setUser] = useState(props.user)
// console.log(props.user)
return (
<div className="App">
{/* <h1>This is app.js</h1> */}
<Route
exact path = "/"
compotent={Home}
/>
<Route
exact path="/login"
component={Login}
/>
<Route
exact path = "/signup"
compotent={Signup}
/>
</div>
);
}
export default App;
Home.js
import React from 'react'
console.log('home loading')
export default function Home() {
console.log('home function')
return (
<div>
<h1>This is home.js</h1>
</div>
)
}
Login.js (this is the only one that renders)
import React from 'react'
import { Link } from 'react-router-dom'
console.log('login loading')
export default function Login() {
console.log('login function loading')
return (
<div>
<h1>Login.js</h1>
<Link to="/auth/google">Login With Google</Link>
</div>
)
}
Signup.js
import React from 'react'
export default function Signup() {
console.log('signup function loading')
return (
<div>
<h1>This is Signup.js</h1>
</div>
)
}
Try to remove spaces exact path = "/" => exact path="/" for both Home and Signup routes
Try this:
import { React, useState } from 'react';
import './App.css';
import { Route, BrowserRouter as Router } from 'react-router-dom'
import Home from './components/Home'
import Login from './components/Login'
import Signup from './components/Signup';
console.log('app loading')
function App() {
// const [user, setUser] = useState(props.user)
// console.log(props.user)
return (
<div className="App">
{/* <h1>This is app.js</h1> */}
<Router>
<Route
exact path = "/"
compotent={Home}
/>
<Route
exact path="/login"
component={Login}
/>
<Route
exact path = "/signup"
compotent={Signup}
/>
</Router>
</div>
);
}
export default App;
This should work
Please restructure your app.jsx with the below changes:
import { React, useState } from 'react';
import './App.css';
import { Route, BrowserRouter as Router } from 'react-router-dom'; //I MADE CHANGE HERE
import Home from './components/Home'
import Login from './components/Login'
import Signup from './components/Signup';
function App() {
console.log('app loading')
return (
<div className="App">
<Router> //I MADE CHANGE HERE
<Route
exact path = "/"
compotent={Home}
/>
<Route
exact path="/login"
component={Login}
/>
<Route
exact path = "/signup"
compotent={Signup}
/>
</Router> //I MADE CHANGE HERE
</div>
);
}
export default App;
I had a spelling mistake in the '/' and '/signup' routes.
I had written 'compo*t*ent=...' instead of 'compo**n**ent'.
The code is now corrected and the compo**n**ents are rendering just find.

Categories