1

I created following with react router.

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 

class Main extends Component {

render() {   
        return ( 
    <Router>
     <Switch>
       <Route exact path='/' component={Content} />   
       <Route path='/user/:id' component={User} /> 
       <Route path='*' component={NotFound} />
     </Switch>  
    </Router>
    );
}

export default Main

I want to open Notfound page if any invalid url.

I tried to open localhost:3000/err but, it will not go to NotFound compoenent.

My notfound component is simple.

import React from 'react';

const NotFound = () => (
    <h2>404 Page Not Found</h2>
);

export default NotFound;

I am using "react-router-dom": "^4.3.1

7
  • You say "I tried to open localhost:3000/err but, it will not got to NotFound component.". What do you get instead? I did just try to use your code (using "react-router-dom": "^4.3.1), and it works just fine (on localhost:3000/err I get "404 Page Not Found"). Commented Jan 15, 2019 at 13:57
  • @MarcoS i got Cannot GET /err Commented Jan 15, 2019 at 13:58
  • Does your project compile successfully? I.e.: do you get something like Compiled successfully! on your yarn start command? And, above all, something like You can now view my-app in the browser. ? Commented Jan 15, 2019 at 14:00
  • @MarcoS Yes. i 「wdm」: Compiled successfully. Commented Jan 15, 2019 at 14:01
  • Does localhost:3000/ works fine? Commented Jan 15, 2019 at 14:02

4 Answers 4

5

Finally, I solved by following solution.

Inside my webpack config file ( webpack.config.js ) i added following:

output: {
    publicPath: '/'
},

devServer: {
    historyApiFallback: true
}
Sign up to request clarification or add additional context in comments.

Comments

0

In order for client-side routing to work, the server needs to always return the same index.html for all routes.

So, localhost:3000/err needs to return your index.html with the client-side router javascript.

4 Comments

I done following in my server.js file. app.get('*', (req, res) => { res.sendFile(path.join(__dirname, './index.html')); });
do you see index.html coming back in devTools?
then, your server (express?) configuration is not correctly returning for all routes.
Actually i have following code. app.get('*', (req, res) => { res.sendFile(path.join(__dirname, './index.html')); }); app.listen(port, function (err) { if (err) { console.log(err); } else { open('http://localhost:' + port); } })
0

Have you tried using Redirect? I am using this in my app and it works perfectly fine. Here is the updated code for your reference-

import {Route, Switch, Redirect } from 'react-router-dom'; 

class Main extends Component {

render() {   
        return ( 
     <Switch>
       <Route exact path='/' component={Content} />   
       <Route path='/user/:id' component={User} /> 
       <Route path="/not-found" render={props => <NotFoundPage />} />
       <Redirect to="not-found" />
     </Switch>  
    );
}

export default Main

Enclose your App inside BrowserRouter.

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import App from './components/app.js'
import styles from './styles/style.css'
import { store } from './stores/store'

ReactDOM.render((
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
), document.getElementById('root'))

Let me know if this helps.

8 Comments

Updated my answer a bit. This should definitely work.
Sorry. No luck. It even stops other component to render
It won't open not found page
I believe you have added the BroswerRouter in your index.js
You should add this to your file where you are bundling the entire app.
|
0
"react-router-dom": "^5.1.2",
<Router history={history}>
  <Switch>
    <Route exact path={[routes.user.details]} component={UserProfile} />
    <Route exact path={[routes.category.collection]} component={CategoryCollection} />
    <Route exact path={[routes.category.details]} component={CategoryDetails} />
    <Route exact path={[routes.product.collection]} component={ProductCollection} />
    <Route exact path={[routes.product.details]} component={ProductDetails} />

    <Route exact path={routes.auth.login} component={Login} />
    <Route exact path={routes.auth.register} component={Register} />
    <Route exact path={routes.auth.resetPassword} component={ResetPassword} />

    <Route
      path="*"
      component={() => {
        if (user.id) {
          return <Redirect to={routes.user.details} />;
        }

        return <Redirect to={routes.auth.login} />;
      }}
    />

  </Switch>
</Router>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.