FYP
2022-09-01 20:00:00

React Integration

It is almost necessary to integrate a front-end framework to improve the development efficiency. This note is a short guide on how to integrate React framework for an IC project.

Dependencies Installation

First, in a new project (refer to the fyp project in this note), install the required typescript compiler:

npm install --save-dev typescript ts-loader

Then install the react modules:

npm install --save react react-dom

Modify Webpack Config

The next step is to modify the webpack.config.js:

Change the entry:

entry: {
  // change .js to .jsx for the use of react
  index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"),
},

And change the module -> rules

module: {
  rules: [
    // add loader for .jsx and .tsx 
    { test: /\.(js|ts)x?$/, loader: "ts-loader" }
  ]
},

Ok, now the modification for webpack.config.js is done.

TSConfig

Then create the tsconfig.json file in the project root with the following content:

{
  "compilerOptions": {
    "target": "es2018",
    "lib": ["ES2018", "DOM"],
    "allowJs": true,
    "jsx": "react",
  },
  "include": ["./src/fyp_frontend/**/*"],
}

Now, all the configurations are done. Then open the default index.html in the front-end canister, replace it with a clean template, here is an example:

Adjust Source Code

<!doctype html>
<html lang="en">
 <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Home</title>
    <base href="/">
 </head>
 <body>
    <div id="app"></div>
 </body>
</html>

The last thing to do is to rename the index.js to index.jsx and start writing react code.

import React from "react"
import { render } from "react-dom"

const Container = () => {
  return (
    <div>
      Hello React! 
    </div>
  )
}

render(<Container />, document.getElementById("app"))

References

Some information in this note come from the following external links: