React Router | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 3

React Router

I was trying to figure out how react router worked under the hood which lead me to a blog post that said it made use of the location and history api so i started to tinker with the location property. My question is if i have a script attached to an index.html and my url is localhost:3000 and I have a js code which is setinterval(() => { if (window.location.href === 'http://localhost:3000/red') console.log('RED'); else if (window.location.href === 'http://localhost:3000/red/two') console.log('DOUBLE TROUBLE'); else console.log('BASIC'); }, 2000); Now i don't really have any /red or even a /red/two directory inside my project just a simple index.html and an index.js file. So now after the index.html has rendered on the page, inside my console tool when i type location.href = "http://localhost:3000/red" it does not throw an error rather it changes the url as expected but the most confusing part is that my "if" statement becomes true which then starts to print out "RED" and this situation also happens when i change my url to http://localhost:3000/red/two it print's out "DOUBLE TROUBLE" PS. I know react-router uses the location and history api i just want to know why the browser is still executing my script when the new location "does not exist". I know this is a lengthy "story" but i am trying to be as descriptive as i can so as to avoid any misunderstanding with my question.

28th Oct 2021, 9:59 PM
1 Respuesta
+ 1
Let me try to structure the answer in a best way possible. Lets see behavior of React-Router: When a link is clicked inside a React-App, it doesn't point to a location, instead the DOM is re-rendered according the route(URL). In other words, the index.html is always static for all the routes, what changes is the body(content), simulating a single page. Hence React is a Single Page Application. React-Router works in switch case statement, as every switch has a default case. The default case for React-Router Switch is an empty DOM without any content. So even though you don't have any content supplied, when you change the URL, the default empty DOM return, and there is no error.. Hope this helps. >_< And please let me know, If I have to rephrase the answer.
12th Nov 2021, 1:16 PM
Zubae - avatar