I am trying to set up routing in my React app. I am not getting any error and the app is not breaking but when I navigate to a new page nothing is displayed. I am using react-router-dom v6 and 'Switch' has been replaced with 'Routes' and component has been replaced with element: https://reacttraining.com/blog/react-router-v6-pre/. It also appears you do not need the leading "/".
EDIT at bottom of page.
http://localhost:3000/Player and http://localhost:3000/* (or anything other than the * ) both render blank screens.
This is the landing page which works fine:
HomePage.tsx
/** @jsxImportSource @emotion/react */
import React from 'react';
import { css } from '@emotion/react';
import logo from '../assets/cyberpunk.png';
export const HomePage = () => (
<div
css={css`
margin: 10px auto 20px auto;
padding: 30px 20px;
max-width: 1000px;
display: flex;
align-items: center;
justify-content: space-between;
`}
>
<div>
<img
src={logo}
alt="Logo"
css={css`
width: 700px;
margin-left: 130px;
`}
/>
<h2>Players</h2>
<button>Select a toon</button>
</div>
</div>
);
This is the player page:
PlayerPage.tsx
import React from 'react';
export const PlayerPage = () => <h2>"One toon"</h2>;
The page not found page:
NotFoundPage.tsx
import React from 'react';
export const NotFoundPage = () => <h2>"Page Not Found"</h2>;
Finally,
App.tsx
/** @jsxImportSource @emotion/react */
import React from 'react';
import { css } from '@emotion/react';
import { Header } from './header';
import { HomePage } from './Views/HomePage';
import { fontFamily, fontSize, gray2 } from './Styles';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { PlayerPage } from './Views/PlayerPage';
import { PlayersPage } from './Views/PlayersPage';
import { PlayerCreatePage } from './Views/PlayerCreatePage';
import { NotFoundPage } from './Views/NotFoundPage';
function App() {
return (
<BrowserRouter>
<div
css={css`
font-family: ${fontFamily};
font-size: ${fontSize};
color: ${gray2};
`}
>
<Header />
<Routes>
<Route path="" element={<HomePage />} />
<Route path="Players" element={<PlayersPage />} />
<Route path="Player" element={<PlayerPage />} />
<Route path="Create" element={<PlayerCreatePage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
Why would the h2 elements in the NotFoundPage and PlayerPage not be being displayed? It acts like I'm navigating to an incorrect route every time.
I fixed it kind of. I remade one of the pages to look like this:
function PlayerCreatePage() {
return (
<div style={{ padding: 20 }}>
<h2>About View</h2>
<p>Lorem ipsum dolor sit amet, consectetur adip.</p>
</div>
);
}
export default PlayerCreatePage;
And this one does show up. Why is that? What is wrong with the other views?