Using React in a multi-page app

后端 未结 6 777
滥情空心
滥情空心 2021-01-29 17:21

I have been playing around with React and so far I really like it. I am building an app with NodeJS and would like to use React for some of the interactive components across the

6条回答
  •  花落未央
    2021-01-29 17:59

    Currently, I am doing something similar.

    The application is not a full React App, I am using React for dynamic Stuff, like CommentBox, which is autark. And can be included at any Point with special params..

    However, all my sub Apps are loaded and included into a single file all.js, so it can be cached by the browser across pages.

    When I need to include an App into the SSR Templates, I just have to include a DIV with the class "__react-root" and a special ID, ( the name of the React App to be rendered )

    The logic is really simple:

    import CommentBox from './apps/CommentBox';
    import OtherApp from './apps/OtherApp';
    
    const APPS = {
      CommentBox,
      OtherApp
    };
    
    function renderAppInElement(el) {
      var App = APPS[el.id];
      if (!App) return;
    
      // get props from elements data attribute, like the post_id
      const props = Object.assign({}, el.dataset);
    
      ReactDOM.render(, el);
    }
    
    document
      .querySelectorAll('.__react-root')
      .forEach(renderAppInElement)
    

    Some Article

    Edit

    Since webpack perfectly supports code-splitting & LazyLoading, I thought it make sense to include an example where you don't need to load all your apps in one bundle, but split them up and load on demand.

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const apps = {
      'One': () => import('./One'),
      'Two': () => import('./Two'),
    }
    
    const renderAppInElement = (el) => {
      if (apps[el.id])  {
        apps[el.id]().then((App) => {
          ReactDOM.render(, el);
        });
      }
    }
    

提交回复
热议问题