Creating an SPA Router in Vanilla JS

แชร์
ฝัง
  • เผยแพร่เมื่อ 7 พ.ย. 2024

ความคิดเห็น • 162

  • @mitch_dev
    @mitch_dev  2 ปีที่แล้ว +75

    I've seen a lot of people experiencing errors when attempting to input a URL to go to a page. If you are experiencing errors, make sure your server is only serving your index page for any request. This will allow your router to load and operate properly. Apologies for not including that part in the video!

    • @leg3ndtariq
      @leg3ndtariq 2 ปีที่แล้ว +11

      u can make another one with this error.pleae.

    • @swatman89
      @swatman89 2 ปีที่แล้ว +3

      you have link to movie that show how to do this?

    • @ReactWithSamwize
      @ReactWithSamwize 2 ปีที่แล้ว

      I believe that is what the parcel-bundler is been used for, right?

    • @ankitaburman5406
      @ankitaburman5406 2 ปีที่แล้ว

      Hello Mitch , this looks really cool. can you tell me if we have three forms into these three paths , and a single submit button to post data to server , will it be possible to make it like that ? I have a small use case to develop so that’s why wanted to check with.

    • @CSCoreDecoded
      @CSCoreDecoded 2 ปีที่แล้ว +1

      can you explaine this point more plz

  • @AliveDeejay
    @AliveDeejay 4 หลายเดือนก่อน +6

    This 3 minute clip just saved me from learning Angular, React, Node.js and TypeScript. I know there are quite a bit differences, but for my purpose this is exactly what i needed, thanks! :D

    • @reze_dev
      @reze_dev 3 หลายเดือนก่อน +1

      I came here for the same reason and use htmx or alpinejs for reactivity

  • @GingLouie
    @GingLouie ปีที่แล้ว +12

    Such a straightforward implementation of vanilla JS routing. THANKS! i had already looked at several tutorials attempting the same. They were across the board clunky and, at times, arcane (at least to me). You saved me many hours of frustration and aggravation.

  • @Mobilemaniaplays
    @Mobilemaniaplays ปีที่แล้ว +1

    Making the clone of Spotify using only vanilla js , this is my favourite video , thanks bro, love from India

  • @life8261
    @life8261 11 หลายเดือนก่อน +1

    Great video, Mitch Dev. Thank you for such a nice and simple video! It's much better to get everything you need for less than 4 minutes than watching my professor's 1.5h lecture which would give me no idea what is going on.

  • @kombokenedy4750
    @kombokenedy4750 2 ปีที่แล้ว +2

    OMG !!! This is the madness i have been looking, Long live Mr. DEV.

  • @severn-master
    @severn-master 6 หลายเดือนก่อน +1

    surprisingly, i found a very clear usecase of vanilla js for routing from non indian youtuber

  • @L3anAv
    @L3anAv 2 ปีที่แล้ว +15

    Very good video and explanation. It was what I was looking for, a simple router in js vanilla. Thanks for sharing. I will be aware of the channel.

  • @JahanKlik
    @JahanKlik 2 ปีที่แล้ว +2

    Wow, amazing!!!
    OMG so clear, so to the point, so short, again wow
    Excellent👏

  • @mauriciolaratro
    @mauriciolaratro ปีที่แล้ว +1

    Thank you for this great contribution, simple and perfect explanation.

  • @abahiduh3246
    @abahiduh3246 ปีที่แล้ว

    is just that u need an extended knowledge of js to do this.... thank you very much

  • @neilgibs6673
    @neilgibs6673 ปีที่แล้ว +1

    This vidéo is great ,direct and clear .
    Thank's it helped a lot

  • @JorgeSanchez-nv2ks
    @JorgeSanchez-nv2ks 2 ปีที่แล้ว +2

    Great video, I've been looking for a simple example like this, thanks for sharing.

  • @Surush_Cyrus
    @Surush_Cyrus ปีที่แล้ว

    Exactly what I was looking for, works great, you the man!

  • @animeworldnetwork1714
    @animeworldnetwork1714 2 ปีที่แล้ว +2

    Man you are awesome... I was looking for this for very long thank you

  • @Fanaro
    @Fanaro 2 ปีที่แล้ว +2

    Dope example. A bit too fast for those who are watching SPAs from scratch for the first time, but thanks a lot for the concise version.

  • @danielfarkas8951
    @danielfarkas8951 2 ปีที่แล้ว +1

    thanks for the upload, clean and straightforward explanation! :)

  • @sonyhellboy6
    @sonyhellboy6 2 ปีที่แล้ว +2

    This helped me a LOT! Thank you man.

  • @antonio_carvalho
    @antonio_carvalho 2 ปีที่แล้ว

    Super excellent video for those like me who like to do most things by hand

  • @kamutabung511
    @kamutabung511 6 หลายเดือนก่อน

    awesome, simple and clear solution

  • @jaimeviloriogreen
    @jaimeviloriogreen 2 ปีที่แล้ว

    Mitch, from now on, I follow you!

  • @josiah_maddux
    @josiah_maddux 2 ปีที่แล้ว +2

    Great video! Real simple and to the point

  • @nalendro_agung
    @nalendro_agung 2 ปีที่แล้ว +5

    thanks for the video, but there's an error when i reload after clicking one of the route nav, any ideas?

  • @GabrielAlejandroZorrilla
    @GabrielAlejandroZorrilla 2 ปีที่แล้ว +4

    Simple way to kickstart a small webapp without all the crrap of framework and npm, etc.

  • @ВалераВласенков-ю2о
    @ВалераВласенков-ю2о 11 หลายเดือนก่อน +2

    still cant get why do we need route function
    Looks like ive got why we need route function. So if we have buttons then we just set click event on them and call route function in callback function, right?

  • @ts8960
    @ts8960 2 ปีที่แล้ว +6

    it only works when clicking the links, but error when doing it through URL

    • @pjf7044
      @pjf7044 2 ปีที่แล้ว +2

      Thats because when you input the URL into the browser, it is actually making a http request to the server. But since is only client side it will not work

    • @sadface
      @sadface 2 ปีที่แล้ว +1

      you probably need to set up your web server (in my case I use Apache, so .htaccess) to use your main index.html page as the 404 page. You're basically always 404'ing, but then handling it by serving up your web app.

  • @ForWork-mj9fv
    @ForWork-mj9fv 3 หลายเดือนก่อน

    Thank you so much for this awesome video 🙏

  • @nikoing
    @nikoing 2 ปีที่แล้ว +3

    It's so nice, clear and perfect this video.
    However, I would like to know what will happen if we refresh the page ?
    i.e « If I'm on (about page) then I refresh, it will go back (to index page) ? »

  • @kbh1301
    @kbh1301 2 ปีที่แล้ว +5

    What are you using to host your local server? I'm using the VSCode extension Live Server and reloading the page or manually entering a path causes an error

    • @mitch_dev
      @mitch_dev  2 ปีที่แล้ว +2

      I also use the live server extension. If you cloned the repo, it should work out of the box if you start the live server on the root html page. If you're recreating it for yourself, make sure your route paths are correct

    • @katarca1120
      @katarca1120 2 ปีที่แล้ว +3

      @@mitch_dev Same problem. I cloned the repo, but still if I manually enter a path it cause an error. I didn't figure out how to fix it.

    • @kdta91
      @kdta91 2 ปีที่แล้ว

      @@katarca1120 haven't found a solution on this

    • @katarca1120
      @katarca1120 2 ปีที่แล้ว +5

      Neither do I. I just want to point out that this is clearly not usable in practice.

    • @kdta91
      @kdta91 2 ปีที่แล้ว

      @@katarca1120 funny thing is I have tried a similar approach with pushState and popState with a node server but manual url entry or refresh works. I still haven't found a solution for this.

  • @nemanjatrivic9505
    @nemanjatrivic9505 3 หลายเดือนก่อน +1

    How to have dynamic urls, like /blogs/1 for example?

  • @magaverde
    @magaverde 27 วันที่ผ่านมา

    THIS HELP SO MUCH! THANK'S

  • @didierbelle3723
    @didierbelle3723 2 ปีที่แล้ว

    This is an awesome video. Thank You.👏

  • @jandeswart1378
    @jandeswart1378 2 ปีที่แล้ว

    This is a very very well made video!

  • @DavidAieta
    @DavidAieta 2 ปีที่แล้ว

    Thanks a lot man, you should upload more videos like this

  • @VictorsTravelvLog
    @VictorsTravelvLog 8 หลายเดือนก่อน

    very nice! though your example does not demonstrate the advantages of client-side routing over server-side routing? fetch still grabs the entire contents of the 3 pages, every time a link is clicked?

  • @TheBeastHaerup
    @TheBeastHaerup 2 ปีที่แล้ว +3

    Edit: Solved - if you are using webpack, remember to set historyApiFallback: true, in the devServer
    Hey Mitch, how can I serve the right page to the URL on page refresh? For example if I navigate to /blog and refresh the page I would get a 404. I have set things up with webpack and all seems to work, just not on page refresh.
    Cheers

  • @nefed-L
    @nefed-L ปีที่แล้ว

    Great tutorial! Thanks!

  • @scubahick
    @scubahick 15 วันที่ผ่านมา

    how about loading scripts when loading those other html files? I am having a problem with setting innerHTML and the JS not working with fetched HTML files.

  • @anthonyapm
    @anthonyapm 2 ปีที่แล้ว +1

    Awesome video.

  • @clevermissfox
    @clevermissfox 10 หลายเดือนก่อน

    Very concise! I am confused where you’re fetching the html for each page from and how there are two const route variables initialized? Assume it has something to do with async/await concepts I haven’t learned yet 😂

  • @ravimone1
    @ravimone1 2 ปีที่แล้ว

    Hey @Mitch Dev, This is awesome, thanks for this video, just a question, Is this how all the SPA's have the router library built-on?

  • @mauriciolaratro
    @mauriciolaratro ปีที่แล้ว +2

    Hello friend, I tried to use this method for a SPA and it worked perfectly, but when I want to use images as "a", the "oneclick" does not work and it is only possible to access the "a" by clicking around the img. But it doesn't work if you click inside it.
    Any advice on how to solve this? I have very little idea of js, so I'm stuck with this problem.

    • @v.saravanavel1824
      @v.saravanavel1824 8 หลายเดือนก่อน

      give the href and onclick to the img tag

  • @John223
    @John223 2 ปีที่แล้ว +14

    This is a cool project, just a small problem. If I go to "/about" and refresh the page, it returns "Cannot GET /about"

    • @akash-kumar737
      @akash-kumar737 ปีที่แล้ว +1

      You need to add redirect to home.

    • @summerboyparag8361
      @summerboyparag8361 11 หลายเดือนก่อน

      Because if we refresh page the route is different from home route is a big problem when you host the app but for this we have solution like longitude and something like like landude in angular using provider
      In javascript there is something like this using this you route is like this 'home/+your route ' using this it solve the problem

  • @itzglitchbot
    @itzglitchbot 2 ปีที่แล้ว +1

    What's the difference between this and a href or window. Replace?

  • @MorganAdair
    @MorganAdair 2 ปีที่แล้ว

    Great explanation!

  • @HelloWorld-tn1tl
    @HelloWorld-tn1tl 2 ปีที่แล้ว

    Great project man !!!

  • @infiniteprogramming
    @infiniteprogramming 2 ปีที่แล้ว

    Please upload more such videos 😊

  • @guy84eilon
    @guy84eilon 2 ปีที่แล้ว +1

    hi! tanks for the video.. have a problem with get elements in the DOM pages, any idea?

    • @nefed-L
      @nefed-L 11 หลายเดือนก่อน

      I use async functions for this.

  • @prometheus5770
    @prometheus5770 2 ปีที่แล้ว

    that's beautiful

  • @developerGorilla
    @developerGorilla ปีที่แล้ว +3

    is window.route = route; neccessary? If neccessary, what for?

    • @LoneWolf-ey1hq
      @LoneWolf-ey1hq ปีที่แล้ว

      This is something I still struggle to figure out.

    • @nefed-L
      @nefed-L 11 หลายเดือนก่อน +1

      I removed it because found somewhere on the internet that it is a bad practice (creating global variables, through assigning them as global object/document properties).

    • @davidestrada3791
      @davidestrada3791 2 หลายเดือนก่อน

      I removed it but it causes the page to reload. Not sure how this is working

  • @jyhadbenyoussef221
    @jyhadbenyoussef221 2 ปีที่แล้ว

    Simple et efficace 👍

  • @muhamad1247
    @muhamad1247 6 หลายเดือนก่อน

    Yeah bro its work thankyou

  • @2005bgva
    @2005bgva ปีที่แล้ว +2

    Hi Mitch, thanks for this video. Maybe could you do the same with a vanilla js created with vite?

  • @Big_Dadaa
    @Big_Dadaa 2 ปีที่แล้ว +1

    Hi Mitch,
    How do we send post requests, I have tried all things but does not work it returns html response

  • @ahmadrazi4746
    @ahmadrazi4746 2 ปีที่แล้ว

    I have a question, can i manipulate the dom with this method? for example i want to make an event listener so that when click the h1 element on the about page it logs "clicked" on the console. Been struggling with that.

  • @frontend_ko
    @frontend_ko 9 หลายเดือนก่อน

    thank you very much

  • @dwchau.254
    @dwchau.254 5 หลายเดือนก่อน

    can u create a dynamic route in vanilla js ? example: /detail/:id --> show id in screen

  • @FabrizioNicosia
    @FabrizioNicosia 2 ปีที่แล้ว

    Thanks a lot man

  • @adarshchakraborty
    @adarshchakraborty 2 ปีที่แล้ว

    Awesome

  • @vibhanshuranjanthakur891
    @vibhanshuranjanthakur891 6 หลายเดือนก่อน

    Can I run this as a static website from S3 or does it need a server to render files?

  • @haidang3806
    @haidang3806 5 หลายเดือนก่อน

    Thanks a lot

  • @abahiduh3246
    @abahiduh3246 ปีที่แล้ว

    wow! Wonderfu

  • @ahmedsamra1320
    @ahmedsamra1320 2 ปีที่แล้ว +1

    greet job but what about go back URL?

  • @juquanmao3969
    @juquanmao3969 ปีที่แล้ว +1

    Thanks for your video. From your code, I can see that handleLocation function is mannuallly triggered in route() function. where it should be triggered by pushState().

    • @juquanmao3969
      @juquanmao3969 ปีที่แล้ว +1

      Here is a modified .js which works for me:
      const route = (event) => {
      event = event || window.event;
      event.preventDefault();
      // pushState method to update the browser's URL during page navigation.
      window.history.pushState({}, "", event.target.href);
      // To trigger window.onPoPState
      window.history.pushState({}, "", event.target.href);
      history.back()
      };
      const routes = {
      404: "/pages/404.html",
      "/": "/pages/index.html",
      "/about": "/pages/about.html",
      "/lorem": "/pages/lorem.html",
      };
      window.onpopstate = () => {

      const path = window.location.pathname;
      const route = routes[path] || routes[404];
      fetch(route)
      .then((res) =>res.text())
      .then (html => document.getElementById("main-page").innerHTML = html)
      .catch(error =>document.getElementById("main-page").innerHTML = 'unexpected error')

      };

  • @juancmuyou
    @juancmuyou 9 หลายเดือนก่อน

    How i can use ejs instead html for SPA?

  • @ReactWithSamwize
    @ReactWithSamwize 2 ปีที่แล้ว

    Hi Mitch, I understand this is a late comment, especially now that parcel-bundler has been replace with Parcel. I was having difficult perfecting the SPA in this video. Everything seems to work fine except when i enter the url via the browser address bar. Can you assist here, please.

    • @TheBeastHaerup
      @TheBeastHaerup 2 ปีที่แล้ว

      I have the same problem, did you find a solution?

  • @usmangill4773
    @usmangill4773 2 ปีที่แล้ว +2

    On refresh. throws error, with no content.

  • @DoveDev
    @DoveDev 2 ปีที่แล้ว

    Hi what about the parameters in url routing to a specific page like single page or a blog page

  • @kangsan2014
    @kangsan2014 ปีที่แล้ว

    How can we write a localhost without any framework or packages in vanilla Javascript? I can nowhere on the internet on how to do that?

  • @jordanfox3782
    @jordanfox3782 2 ปีที่แล้ว +1

    This is great, but then how would we link a different javascript file to each html page so we could have an actual application logic instead of just views?

    • @zodeyack1
      @zodeyack1 2 ปีที่แล้ว

      You can add a tag inside of each html file

    • @Sedri14
      @Sedri14 ปีที่แล้ว

      @@zodeyack1 I tried this, it doesn't work :(

    • @nefed-L
      @nefed-L 11 หลายเดือนก่อน

      U should use js modules instead. Connect all modules to main.js with import/export keywords.

  • @taiethkl
    @taiethkl 10 หลายเดือนก่อน

    Thank you

  • @katerynananyzniuk
    @katerynananyzniuk 2 ปีที่แล้ว

    What should I do or change if I want to use js modules (smth.js which build html page) instead of using .html files?

    • @mitch_dev
      @mitch_dev  2 ปีที่แล้ว +1

      If you're building an HTML string in JS, you can just use the string generated when setting 'innerHTML'. You can define that functionality in another JS file and require it in your router to keep it clean if desired

  • @hartono9583
    @hartono9583 11 หลายเดือนก่อน

    how if in html run javascript fuction and fetch api? like product page?? please tutorial?

  • @jaimeviloriogreen
    @jaimeviloriogreen 2 ปีที่แล้ว +2

    For those who have problem when the page refresh while insert the url via the browser , the solution is to do the in the config of your web server, in my case nginx:
    location / {
    try_files $uri $uri /index.html =404;
    }
    In my case, this resolved this problem.
    Excuse my english, is not very good looking!

  • @Kewledgykid
    @Kewledgykid 2 ปีที่แล้ว +1

    Does anyone how i can make it work on GitHub pages? Its working fine on my local after editing the live server settings

    • @paulofernando78
      @paulofernando78 ปีที่แล้ว +1

      Familiar with Node JS?

    • @nefed-L
      @nefed-L 11 หลายเดือนก่อน

      I am not. Could you give some suggestions? Where should i start? I should write my own server on node js and add server file to my repo? Is it correct?

  • @rejolu
    @rejolu 2 ปีที่แล้ว

    A great it is, the answer of my problem. But now, there's a another problem when Refreshing my browser it's shows Error file not found. I hope there's something answer on it

  • @JavadRezaii
    @JavadRezaii ปีที่แล้ว

    I did it all , links are working but when I add '/about' to my website url it says page not found 404 ( not my own 404 page )

  • @a-z-n-b-a-i
    @a-z-n-b-a-i ปีที่แล้ว

    thanks for the tutorial. unfortunately on refresh it throws a "Cannot GET" message

  • @cCcesSsarRr
    @cCcesSsarRr ปีที่แล้ว

    Heeelp!!, How can I use it with parameters?

  • @rahff99
    @rahff99 11 หลายเดือนก่อน

    window.event is deprecated, I don't found any alternative.

  • @whoIsV
    @whoIsV ปีที่แล้ว

    What does window.route = route do?

  • @clickbaitpolice9792
    @clickbaitpolice9792 2 ปีที่แล้ว

    hi, im working with python + flask on the backend. with the js file, im getting not found error when clicking the links. i think the issue lies in the const routes function. ive tried so many different paths but i cant get it to work

    • @Nodsaibot
      @Nodsaibot ปีที่แล้ว

      you must redirect all requests to the index, or forget about that and use #hashes instead /#about

    • @lexmachina8961
      @lexmachina8961 ปีที่แล้ว

      ​@@Nodsaibot can you give a snippet to show how to redirect to the index based on the code provided? Thanks

  • @MundoDeHector
    @MundoDeHector 2 ปีที่แล้ว

    Wow great.. , well I want to implement to typescript , but I get some errors .. because some code I have null ..., well is possible transform to typescript ..? , but thank you.. nice code.

  • @Nodsaibot
    @Nodsaibot ปีที่แล้ว +1

    that URL scheme will cause 404 errors, you need to rewrite all requests to the index or redirect 404s to the index, or just use Hashes instead

    • @lexmachina8961
      @lexmachina8961 ปีที่แล้ว

      can you give a snippet to show how to redirect to the index based on the code provided? Thanks

  • @jpdoshi2811
    @jpdoshi2811 2 ปีที่แล้ว

    how are u hosting the html on local server ?

  • @AdvaTced
    @AdvaTced 2 ปีที่แล้ว +1

    you should not use the .html for this little changes and get the whole html page (it's inefficient to do it), in exchange you could use the rest api for that and "refresh" the page.
    but it's a greate video!

  • @zlackbiro
    @zlackbiro 2 ปีที่แล้ว

    Yes, but instead of calling fetch, use your class to prepare your template and set inner html in root 🙂

    • @alexb.9252
      @alexb.9252 11 หลายเดือนก่อน

      what?

  • @renatolins4670
    @renatolins4670 ปีที่แล้ว

    This tutorial is just awesome, but in my case, when I refreshe the page in any of the routes (that is not the home), it just doesnt load.. I see the message: "Cannot GET"

  • @arimos3136
    @arimos3136 ปีที่แล้ว

    Thx.

  • @MarquisDeSang
    @MarquisDeSang ปีที่แล้ว +1

    no matter what I do, it will navigate to the other page loosing everything.

  • @user-xo1nw5vm9l
    @user-xo1nw5vm9l 2 ปีที่แล้ว

    Спасибо

  • @pjf7044
    @pjf7044 2 ปีที่แล้ว

    Im curious why someone would do this instead of just creating some content within the same index.html and creating some function that renders or toggles that content as visible or not?

    • @mitch_dev
      @mitch_dev  2 ปีที่แล้ว +2

      That is a 100% viable solution. The drawback to something like that is an extremely large index.html file if your site is to have a lot of content, which can be cumbersome to maintain. Fine for the user, bad for the developer. There is no 100% right or wrong answer when coming up with a solution for routing, they all have pros and cons

  • @NicoHeinrich
    @NicoHeinrich 2 ปีที่แล้ว

    Do I still have to redirect all requests to the root?

    • @mitch_dev
      @mitch_dev  2 ปีที่แล้ว +1

      Yes, all requests should serve the root page. This allows the router to work as expected, and why some people may be experiencing errors when attempting to use the URL bar to navigate

    • @NicoHeinrich
      @NicoHeinrich 2 ปีที่แล้ว

      @@mitch_dev I think you don't make it clear enough (if at all) in your video. Maybe make a second video with the # method as well.

    • @mitch_dev
      @mitch_dev  2 ปีที่แล้ว

      @@NicoHeinrich You're right, I forgot I had that setting on my live server so didn't include it in the video (my bad!). I may do another video with the hash router, but I personally do not think it is a good design decision so we'll see on that one

    • @NicoHeinrich
      @NicoHeinrich 2 ปีที่แล้ว

      @@mitch_dev it definitely is less aesthetically pleasing but also less restrictive and way easier to implement.

    • @NicoHeinrich
      @NicoHeinrich 2 ปีที่แล้ว

      Also, for the home page I don't use a link but a function that resets the url via pushstate (instead of linking to an empty hash). For it to work though you have to initiate your router function as well. Makes the hash router a lot prettier in my opinion.

  • @clipmart1
    @clipmart1 หลายเดือนก่อน

    Load big html css it goes slow

  • @sespis2r
    @sespis2r ปีที่แล้ว

    I wanted かめりあ - Routing SPA what is this youtube

  • @Potato-h2w2s
    @Potato-h2w2s 2 ปีที่แล้ว

    how we can implement an individual detail page, for examples for every of 100 posts

  • @nikilshetty6719
    @nikilshetty6719 16 วันที่ผ่านมา

    Vanilla js routing

  • @alishertuymurodov9568
    @alishertuymurodov9568 2 ปีที่แล้ว +1

    Не удалось скачать видео

  • @TheBorninmotion
    @TheBorninmotion 2 ปีที่แล้ว

    is it seo friendly ?

  • @ichsistemas5326
    @ichsistemas5326 2 ปีที่แล้ว

    Not everything is frameworks!