Codewarlock Codewarlock - 1 month ago 16
Node.js Question

Building a big single-page application on top of React and NodeJS: How to handle view/components?

I'm trying to setup a single-page application on top of React and NodeJS but i can't figure How to handle views and app modules.

Let's analyze this case:

I need a login panel so an user can be authenticated.

Let's suppose this panel is my app-entry point.

Based on what i have learned actually, i should write a component for it and then i have to write an async call or a socket to an API auth route which will return an eventual auth token.

What is the next step considering i need to show the "Real application" After an user is logged in?

Let's suppose i have a module to show registered users list.

Usually, using jQuery i append, via async requests, parts of HTML (views) to the client-side body after any kind of request.

So, if the user asks for a list of users i Just return it as json and then i edit the DOM to append a row for any returned item.

What should i do with React? Shall i have to prepare a component for the users list (the state of the component) (and for any kind of module) and to show it after an user is logged in, hiding the login itself?

Following this idea should i make a file "components.js" to send to the client-side containing every single component the app could use? Or is there a way to push components from server-side only when they are needed?

I hope i have explained myself. My English is not awesome.

Answer

For managing entire sections of content to users (in your case unauthenticated v.s. Authenticated state, consider using a routing system. The preferred is via react-router.

A routing system manages which component (think of screens as components) is rendered depending on the path your user is on. It can also handle redirections.

For example:

  • / displays the login page
  • /app displays the authenticated state, say a dashboard.

Or:

  • / displays a landing page with a link to login
  • /login shows the login page
  • /app displays the authenticated dashboard

Or:

  • / redirects users to /login for unauthenticated users, and shows the dashboard for authenticated users
  • /login shows the login page

Take note redirection here does not refer to the traditional redirect which required a new request and response (page refresh) it is all handled on the client side.