Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

54
Views
How to use React for individual site components

Given the following scenario, how can I use React/Preact components in my project:

  • The main/header content is generated using Django (or static html) templates
  • I want to use React to generate the sidebar and footer components, depending on the page it is sitting on.

I think the following would work, but I don't know how to split or load the bundles according along the following lines:

  • Load React/React-dom bundle on every page
  • Load page specific bundles on demand, where needed

How can I bundle single components up using webpack for use in static html pages and display them where needed? How do I configure webpack for that?

8 months ago · Santiago Trujillo
1 answers
Answer question

0

Essentially you transpile React from a bunch of JS/JSX files into one JS script (using Babel), which is then loaded in your html document. So it'd be something like this:

<html>
  <head>
    // Usual head section stuff
  </head>

  <body>
    <div id="header">
      This is the Django site header
    </div>

    <div id="sidebar_root" />

    <div>
      Blah blah all the site's body content from Django
    </div>

    <div id="footer_root" />

    <script src="react_sidebar.js" />
    <script src="react_footer.js" />
  </body>
</html>

And you'd have you React components (which would have a bunch of sub-components), one of which is rendered into "react_sidebar.js" and the other into "react_footer.js". So those components would be in React and the others would be Django.

So in order to load React bundle scripts on demand, you just need to include the script and the div which acts as its root.

P.S.

If you were always loading the sidebar and footer together (i.e. never just one or the other bur always both) you could combine them React DOM rendering into one script, so you'd only have to include one script in your html

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.