'creating a 404 page with react
Ok so I am working on making a 404 page for react but I don't know how to implement it properly this is what my code looks like
<Router>
<Switch>
<main className={`app ${isDark ? 'app--dark' : ''}`}>
<ProtectedRoute
path="/conversations"
component={() => (
<Home colorMode={isDark} toggleColorMode={toggleColorMode} />
)}
/>
<Route path="/login" component={LoginPage} />
<Route path="/devnotes" component={Devnotes} />
<ProtectedRoute path="/userinfo" component={UserInfo} />
<ProtectedRoute
path="/settings"
component={() => (
<Setting colorMode={isDark} toggleColorMode={toggleColorMode} />
)}
/>
<ProtectedRoute
path="/developerhub"
component={() => (
<Developerhub
className="devhub"
colorMode={isDark}
toggleColorMode={toggleColorMode}
/>
)}
/>
<Redirect to="/conversations" />
<Route path="*">
<FourOhFour />
</Route>
</main>
</Switch>
</Router>;
I watched quite a bit of youtube videos on how to do it and they all said for the path to be *, which is fine but I also don't want the 404 page showing up on all pages I just want it to show up on the ones that don't exist. Does anyone have a solution to this?
Solution 1:[1]
The issue here is that main element is between the Switch that exclusively matches and renders Route components and the Route components that are now inclusively matched and rendered because they aren't directly rendered by a Switch.
Move the Switch component into the main element. Also, don't use the component prop if rendering a component via a function, use the render prop function so the routed components are remounted when this parent component rerenders. Remove the Redirect unless you have a specific path you want to redirect from as it's currently redirecting any path not already matched above in the Switch and you won't hit the 404 path.
<Router>
<main className={`app ${isDark ? "app--dark" : ""}`}>
<Switch>
<ProtectedRoute
path="/conversations"
render={() => (
<Home
colorMode={isDark}
toggleColorMode={toggleColorMode}
/>
)}
/>
<Route path="/login" component={LoginPage}/>
<Route path="/devnotes" component={Devnotes}/>
<ProtectedRoute path="/userinfo" component={UserInfo}/>
<ProtectedRoute
path="/settings"
render={() => (
<Setting colorMode={isDark} toggleColorMode={toggleColorMode}/>
)}
/>
<ProtectedRoute
path="/developerhub"
render={() => (
<Developerhub
className='devhub'
colorMode={isDark}
toggleColorMode={toggleColorMode}
/>
)}
/>
// <Redirect to="/conversations"/> remove this as it will block the 404 route below
<Route path='*'>
<FourOhFour />
</Route>
</Switch>
</main>
</Router>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
