react-router switch not working as expected












0















I'm learning react and got stuck at react-routes



consider the following:



import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" exact component={HelloWorld} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
);
};

function NoMatch({ location }) {
return (
<div>
<h3>
No match found
</h3>
</div>
);
}

export default Root;


on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found










share|improve this question























  • Does <Route path="*" component={NoMatch} /> work?

    – Andy
    Dec 29 '18 at 18:30











  • Nope, issue still persist

    – Bhavay Anand
    Dec 29 '18 at 18:32











  • which version or react-router-dom are you using?

    – quirimmo
    Dec 29 '18 at 18:33











  • it's react-router-dom@4.3.1

    – Bhavay Anand
    Dec 29 '18 at 18:38











  • are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

    – Henry Woody
    Dec 29 '18 at 18:49


















0















I'm learning react and got stuck at react-routes



consider the following:



import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" exact component={HelloWorld} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
);
};

function NoMatch({ location }) {
return (
<div>
<h3>
No match found
</h3>
</div>
);
}

export default Root;


on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found










share|improve this question























  • Does <Route path="*" component={NoMatch} /> work?

    – Andy
    Dec 29 '18 at 18:30











  • Nope, issue still persist

    – Bhavay Anand
    Dec 29 '18 at 18:32











  • which version or react-router-dom are you using?

    – quirimmo
    Dec 29 '18 at 18:33











  • it's react-router-dom@4.3.1

    – Bhavay Anand
    Dec 29 '18 at 18:38











  • are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

    – Henry Woody
    Dec 29 '18 at 18:49
















0












0








0








I'm learning react and got stuck at react-routes



consider the following:



import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" exact component={HelloWorld} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
);
};

function NoMatch({ location }) {
return (
<div>
<h3>
No match found
</h3>
</div>
);
}

export default Root;


on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found










share|improve this question














I'm learning react and got stuck at react-routes



consider the following:



import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" exact component={HelloWorld} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
);
};

function NoMatch({ location }) {
return (
<div>
<h3>
No match found
</h3>
</div>
);
}

export default Root;


on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found







javascript reactjs react-router react-router-dom react-component






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 29 '18 at 18:27









Bhavay AnandBhavay Anand

24




24













  • Does <Route path="*" component={NoMatch} /> work?

    – Andy
    Dec 29 '18 at 18:30











  • Nope, issue still persist

    – Bhavay Anand
    Dec 29 '18 at 18:32











  • which version or react-router-dom are you using?

    – quirimmo
    Dec 29 '18 at 18:33











  • it's react-router-dom@4.3.1

    – Bhavay Anand
    Dec 29 '18 at 18:38











  • are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

    – Henry Woody
    Dec 29 '18 at 18:49





















  • Does <Route path="*" component={NoMatch} /> work?

    – Andy
    Dec 29 '18 at 18:30











  • Nope, issue still persist

    – Bhavay Anand
    Dec 29 '18 at 18:32











  • which version or react-router-dom are you using?

    – quirimmo
    Dec 29 '18 at 18:33











  • it's react-router-dom@4.3.1

    – Bhavay Anand
    Dec 29 '18 at 18:38











  • are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

    – Henry Woody
    Dec 29 '18 at 18:49



















Does <Route path="*" component={NoMatch} /> work?

– Andy
Dec 29 '18 at 18:30





Does <Route path="*" component={NoMatch} /> work?

– Andy
Dec 29 '18 at 18:30













Nope, issue still persist

– Bhavay Anand
Dec 29 '18 at 18:32





Nope, issue still persist

– Bhavay Anand
Dec 29 '18 at 18:32













which version or react-router-dom are you using?

– quirimmo
Dec 29 '18 at 18:33





which version or react-router-dom are you using?

– quirimmo
Dec 29 '18 at 18:33













it's react-router-dom@4.3.1

– Bhavay Anand
Dec 29 '18 at 18:38





it's react-router-dom@4.3.1

– Bhavay Anand
Dec 29 '18 at 18:38













are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

– Henry Woody
Dec 29 '18 at 18:49







are you getting there via a Link component (from React Router) or direct through the url? If direct, can you make a Link to '/abc' and see what happens?

– Henry Woody
Dec 29 '18 at 18:49














4 Answers
4






active

oldest

votes


















0














Have a look into the sandbox it will help you:



https://codesandbox.io/s/py114mqzj0



Please upgrade your dependencies as follows:



"dependencies": {
"react": "16.5.2",
"react-dom": "16.5.2",
"react-router-dom": "4.3.1",
},





share|improve this answer

































    0














    The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.






    share|improve this answer































      0














      This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.



      Fix 1



      You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.



      The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.



      Fix 2



      Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.






      share|improve this answer































        -1














        This seems to be working fine for me with latest React and react-router-dom.



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

        const HelloWorld = () => {
        return <div>Hello World</div>;
        };

        const Root = () => {
        return (
        <BrowserRouter>
        <div>
        <Switch>
        <Route path='/' exact component={HelloWorld} />
        <Route component={NoMatch} />
        </Switch>
        </div>
        </BrowserRouter>
        );
        };

        function NoMatch() {
        return (
        <div>
        <h3>No match found</h3>
        </div>
        );
        }

        export default Root;


        Code sandbox link to try it out






        share|improve this answer


























        • Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

          – Bhavay Anand
          Dec 29 '18 at 19:10











        • historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

          – Vrle
          Dec 29 '18 at 19:13











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53972254%2freact-router-switch-not-working-as-expected%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Have a look into the sandbox it will help you:



        https://codesandbox.io/s/py114mqzj0



        Please upgrade your dependencies as follows:



        "dependencies": {
        "react": "16.5.2",
        "react-dom": "16.5.2",
        "react-router-dom": "4.3.1",
        },





        share|improve this answer






























          0














          Have a look into the sandbox it will help you:



          https://codesandbox.io/s/py114mqzj0



          Please upgrade your dependencies as follows:



          "dependencies": {
          "react": "16.5.2",
          "react-dom": "16.5.2",
          "react-router-dom": "4.3.1",
          },





          share|improve this answer




























            0












            0








            0







            Have a look into the sandbox it will help you:



            https://codesandbox.io/s/py114mqzj0



            Please upgrade your dependencies as follows:



            "dependencies": {
            "react": "16.5.2",
            "react-dom": "16.5.2",
            "react-router-dom": "4.3.1",
            },





            share|improve this answer















            Have a look into the sandbox it will help you:



            https://codesandbox.io/s/py114mqzj0



            Please upgrade your dependencies as follows:



            "dependencies": {
            "react": "16.5.2",
            "react-dom": "16.5.2",
            "react-router-dom": "4.3.1",
            },






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 29 '18 at 18:44

























            answered Dec 29 '18 at 18:37









            Piyush ZalaniPiyush Zalani

            734317




            734317

























                0














                The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.






                share|improve this answer




























                  0














                  The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.






                  share|improve this answer


























                    0












                    0








                    0







                    The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.






                    share|improve this answer













                    The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 29 '18 at 19:20









                    Bhavay AnandBhavay Anand

                    24




                    24























                        0














                        This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.



                        Fix 1



                        You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.



                        The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.



                        Fix 2



                        Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.






                        share|improve this answer




























                          0














                          This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.



                          Fix 1



                          You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.



                          The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.



                          Fix 2



                          Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.






                          share|improve this answer


























                            0












                            0








                            0







                            This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.



                            Fix 1



                            You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.



                            The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.



                            Fix 2



                            Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.






                            share|improve this answer













                            This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.



                            Fix 1



                            You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.



                            The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.



                            Fix 2



                            Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 29 '18 at 22:39









                            DeryckDeryck

                            6,42411640




                            6,42411640























                                -1














                                This seems to be working fine for me with latest React and react-router-dom.



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

                                const HelloWorld = () => {
                                return <div>Hello World</div>;
                                };

                                const Root = () => {
                                return (
                                <BrowserRouter>
                                <div>
                                <Switch>
                                <Route path='/' exact component={HelloWorld} />
                                <Route component={NoMatch} />
                                </Switch>
                                </div>
                                </BrowserRouter>
                                );
                                };

                                function NoMatch() {
                                return (
                                <div>
                                <h3>No match found</h3>
                                </div>
                                );
                                }

                                export default Root;


                                Code sandbox link to try it out






                                share|improve this answer


























                                • Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                  – Bhavay Anand
                                  Dec 29 '18 at 19:10











                                • historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                  – Vrle
                                  Dec 29 '18 at 19:13
















                                -1














                                This seems to be working fine for me with latest React and react-router-dom.



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

                                const HelloWorld = () => {
                                return <div>Hello World</div>;
                                };

                                const Root = () => {
                                return (
                                <BrowserRouter>
                                <div>
                                <Switch>
                                <Route path='/' exact component={HelloWorld} />
                                <Route component={NoMatch} />
                                </Switch>
                                </div>
                                </BrowserRouter>
                                );
                                };

                                function NoMatch() {
                                return (
                                <div>
                                <h3>No match found</h3>
                                </div>
                                );
                                }

                                export default Root;


                                Code sandbox link to try it out






                                share|improve this answer


























                                • Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                  – Bhavay Anand
                                  Dec 29 '18 at 19:10











                                • historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                  – Vrle
                                  Dec 29 '18 at 19:13














                                -1












                                -1








                                -1







                                This seems to be working fine for me with latest React and react-router-dom.



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

                                const HelloWorld = () => {
                                return <div>Hello World</div>;
                                };

                                const Root = () => {
                                return (
                                <BrowserRouter>
                                <div>
                                <Switch>
                                <Route path='/' exact component={HelloWorld} />
                                <Route component={NoMatch} />
                                </Switch>
                                </div>
                                </BrowserRouter>
                                );
                                };

                                function NoMatch() {
                                return (
                                <div>
                                <h3>No match found</h3>
                                </div>
                                );
                                }

                                export default Root;


                                Code sandbox link to try it out






                                share|improve this answer















                                This seems to be working fine for me with latest React and react-router-dom.



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

                                const HelloWorld = () => {
                                return <div>Hello World</div>;
                                };

                                const Root = () => {
                                return (
                                <BrowserRouter>
                                <div>
                                <Switch>
                                <Route path='/' exact component={HelloWorld} />
                                <Route component={NoMatch} />
                                </Switch>
                                </div>
                                </BrowserRouter>
                                );
                                };

                                function NoMatch() {
                                return (
                                <div>
                                <h3>No match found</h3>
                                </div>
                                );
                                }

                                export default Root;


                                Code sandbox link to try it out







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 29 '18 at 18:48

























                                answered Dec 29 '18 at 18:36









                                VrleVrle

                                534515




                                534515













                                • Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                  – Bhavay Anand
                                  Dec 29 '18 at 19:10











                                • historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                  – Vrle
                                  Dec 29 '18 at 19:13



















                                • Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                  – Bhavay Anand
                                  Dec 29 '18 at 19:10











                                • historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                  – Vrle
                                  Dec 29 '18 at 19:13

















                                Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                – Bhavay Anand
                                Dec 29 '18 at 19:10





                                Thanks for the solution, actually I was using webpack configurations instead of create-react-app so webpack config requires devServer: {historyApiFallback: true,} for react routes. I don't what it does but adding this in webpack config file resolves the issue.

                                – Bhavay Anand
                                Dec 29 '18 at 19:10













                                historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                – Vrle
                                Dec 29 '18 at 19:13





                                historyApiFallback always sends responses to your index. It's required for BrowserRouter on SPAs. The HashRouter can work without the historyApiFallback, but you get those ugly hashes /#/ inside your uri.

                                – Vrle
                                Dec 29 '18 at 19:13


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53972254%2freact-router-switch-not-working-as-expected%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas