Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does react render multiple pages in app.js using react-router?

I'm trying to create a multi-page react application. Is react-router right way to go?

Since there is only one HTML file named, index.HTML that pulls the rendered jsx code from app.js's component. And even though we can have the feel of multiple page using react-route; technically isn't it only one-page application that react creates?

import React from 'react';
import { BrowerRoute as Router, Route } from 'react-router-dom';
import App from './components/About';
import Home from './components/Home';
import Contact from './components/News';
import './App.css'

class App extends Component {
  render() {
    return (
       <Router>
        <div>
        <Route exact path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route path='/news' component={News} />
        <div> 
      </Router>
      
    );
  }
}

export default App;

Doesn't this mean all the pages must be rendered and loaded before displaying specific page? or am I wrong?

Is there a better way?

like image 856
Riwaj Chalise Avatar asked Mar 30 '19 17:03

Riwaj Chalise


2 Answers

React is a Single Page Application (SPA) frontend framework. An intuitive definition of what this means is that your web app needs only 1 page load. However, an SPA can support the user experience of having "multiple pages", including changing the url path: e.g. www.app.com/home -> www.app.com/about. That is what the react router offers, the ability to associate different url paths to react components (www.app.com/home renders the Home component).

The underlying principle of SPAs is that instead of serving a new page, only one html page is served and the framework handles all UI changes via direct DOM manipulation.

Doesn't this mean all the pages must be rendered before the HTML loads the page? or am I wrong?

No, only the component associated to particular route/url-matcher will be rendered at any given time.

like image 182
jlau Avatar answered Oct 13 '22 01:10

jlau


Yep, keep with React Router.

Nops, only the page/component route that match the router path will be rendered.

But let me clarify it...

When you say:

all the pages must be rendered before the HTML loads

I believe you mean loaded (the website/app files) and not rendered.

Render means that the route page/component will exist in DOM. So, loaded yes, rendered nope.

You can optimize it using React Code-Splitting and/or playing with Webpack Split Chunks.

like image 29
Wander Lima Avatar answered Oct 13 '22 01:10

Wander Lima