pomber / didact

A DIY guide to build your own React
https://pomb.us/build-your-own-react/
6.29k stars 531 forks source link

Router implementation? #50

Closed Neyunse closed 1 year ago

Neyunse commented 1 year ago

Any idea how implementate Routing like nextjs or react-router-dom?

franciscop commented 1 year ago

I made a small alternative to react-router-dom, which is probably useful if you want to learn but not go into the massive project that RRD is:

https://github.com/franciscop/crossroad/tree/master/src

You have 3 high-element logic bits for a Router (conceptually):

  1. <Router> The wrapper of it all; the central place where you parse the current URL, listen for event updates on the History API, etc. It will usually be a Provider with context for all other elements.
  2. <Route path="x" component={Y} /> this will extract the current path from the context (which was parsed and provided by Router), then compare the string path with the current path and render the component or return null. It is a glorified if at the end of the day.
  3. <Link>, history API, or similar (in my library it's just <a> that get .addEventListener() + preventDefault). A way of navigating to a new page. Link in react router is a glorified history.pushState()

So basically the big important one is the Router, that parses the current URL, providing its state to any component, and manages the navigation events. Everything else can be composed from these principles.

Neyunse commented 1 year ago

I made a small alternative to react-router-dom, which is probably useful if you want to learn but not go into the massive project that RRD is:

https://github.com/franciscop/crossroad/tree/master/src

You have 3 high-element logic bits for a Router (conceptually):

  1. <Router> The wrapper of it all; the central place where you parse the current URL, listen for event updates on the History API, etc. It will usually be a Provider with context for all other elements.
  2. <Route path="x" component={Y} /> this will extract the current path from the context (which was parsed and provided by Router), then compare the string path with the current path and render the component or return null. It is a glorified if at the end of the day.
  3. <Link>, history API, or similar (in my library it's just <a> that get .addEventListener() + preventDefault). A way of navigating to a new page. Link in react router is a glorified history.pushState()

So basically the big important one is the Router, that parses the current URL, providing its state to any component, and manages the navigation events. Everything else can be composed from these principles.

But is it possible to achieve this without using react lib? @franciscop

franciscop commented 1 year ago

Yes

Neyunse commented 1 year ago

@franciscop I tried it without react and could not create a decent integration. I could only move within the page and if I loaded a url for example /home, the site broke.