React Route vs Express Routes

Hi, can anyone help clarify for me when to use react router vs express routes for a full stack project?

Currently I have a mongo backend that I can send to my react front end using fetch. However using react router, I can’t figure out how to pass the state as props to my final component to be displayed.

SO it has me wondering if I should grab this data on the back end.

the syntax for <Route path = “XXX” component = {My Component} /> doesn’t allow for props to be passed. What am I missing? I can share some code if it helps.

React Router is there to allow you to split up your app UI into sections, it is purely a UI abstraction. Express router is there to allow you to define endpoints for different resources.

So as an example, say your app is just a form with multiple pages. In that form you have some data that needs to be validated/saved/etc as a user goes through it - say the user email and address needs to be checked.

In express, you have a single route for the HTML index page. That route can set up the page with the initial props to set up the React form.

In react you would have multiple routes, but they are purely a UI thing; it’s still the same page. You can hook into them to run logic though, like fetching data before the app updates to the next page. So yes it doesn’t allow props to be passed, but the component update functions are there to allow you to update state, and you pull from the backend there.

In express you would also have a set of routes that just return JSON. So when a user enters their email then clicks a button to move to the next page of the form, you could hit the relevant Express route that validates the data and returns a blob of JSON you can use to update the state of the React app. Same with the address. Then when the user hits submit, it hits that submit route in the Express app, which saves to the DB and returns something that says everything’s ok or its failed.

5 Likes

That validate my suspicions. I wish this was conveyed clearly on pages 1 of google search results! I guess it’s up to me to decided how big of a json blob to send to react for various actions in the front end vs querying the database again

This is one of those things that it’s quite hard to grok as a beginner. I found it a bit baffling when I was starting out. But it’s difficult to Google because you’re asking “how do I make the backend and the front-end talk to each other with my very particular setup, using this very specific set of technologies, for this highly specific purpose”. The results that come up are always someone trying to solve their specific problem, so there are always subtle differences even when you find something that seems to almost match your problem.

2 Likes