3.2 How does "Dfinity Frontend" customize the frontend for your dapp? (React+JSX)

3.2 How does "Dfinity Frontend" customize the frontend for your dapp? (React+JSX)

step:

create a new project

Create a new project and move the current directory of the command terminal to the project root directory;

Install the React framework for the project

  • Install the React module by running:
npm install --save react react-dom
  • Install the required TypeScript language compiler loader by running:
npm install --save-dev typescript ts-loader
  • Install the required CSS loaders by running:
npm install --save-dev style-loader css-loader

If npm installa command reports a vulnerability, you may also want to run npm audit fixthe command to attempt to fix the reported vulnerability before proceeding.

NOTE
As an alternative to installing these modules, you can edit the default
package.jsonfile to add the project's dependencies
{
    
    
  "name": "contacts_assets",
  "version": "0.1.0",
  "description": "",
  "keywords": [],
  "scripts": {
    
    
    "build": "webpack"
  },
  "devDependencies": {
    
    
    "assert": "2.0.0",
    "buffer": "6.0.3",
    "css-loader": "^5.2.1",
    "events": "3.3.0",
    "html-webpack-plugin": "5.3.1",
    "process": "0.11.10",
    "stream-browserify": "3.0.0",
    "style-loader": "^2.0.0",
    "terser-webpack-plugin": "5.1.1",
    "ts-loader": "^8.1.0",
    "typescript": "^4.2.4",
    "util": "0.12.3",
    "webpack-cli": "4.5.0",
    "webpack": "5.24.4"
  },
  "dependencies": {
    
    
    "@dfinity/agent": "0.10.0",
    "@dfinity/candid": "0.10.0",
    "@dfinity/principal": "0.10.0",
    "react-dom": "^17.0.2",
    "react": "^17.0.2"
  }
}

The version of the JavaScript agent in this example package.json file is 0.10.0. However, in most cases you want to use the latest version of the agent available. When you create a new project, dfx newthe command automatically retrieves the latest version of the JavaScript agent for you. npm install --save @dfinity/agentYou can also manually retrieve the latest version by running the command after creating the project .

modify default program

1. Open the file in a text editor src/contacts/main.moand delete the existing content.

2. Copy and paste the sample code below into the file:

import List "mo:base/List";
import AssocList "mo:base/AssocList";

actor Contact {
    
    

  var contacts : ContactsMap = List.nil();

  type Name = Text;
  type Phone = Nat;

  type Entry = {
    
    
    name : Name;
    address1 : Text;
    address2 : Text;
    email : Text;
    phone : Phone;
  };

  type ContactsMap = AssocList.AssocList<Name, Entry>;

  func nameEq(lhs : Name, rhs : Name) : Bool {
    
    
    return lhs == rhs;
  };

  public func insert(name : Name, address1 : Text, address2 : Text, email : Text, phone : Phone) : async () {
    
    
     let newEntry : Entry = {
    
    
       name;
       address1;
       address2;
       email;
       phone;
     };

     let (newContacts, _) = AssocList.replace(
       contacts,
       name,
       func(n: Name, m: Name) : Bool {
    
     n == m },
       ?newEntry
     );
     contacts := newContacts;
  };

  public query func lookup(name : Name) : async ?Entry {
    
    
    return AssocList.find(contacts, name, nameEq);
  };
};

3. Save your changes and close the main.mo file to continue.

Modify the front-end file

Now it's time to create a new front end for the program.

1. Open the webpack configuration file ( ) in a text editor webpack.config.js.

2. Modify the front-end entry and replace the default index.html with index.jsx.

entry: {
    
    
  // The frontend.entrypoint points to the HTML file for this build, so we need
  // to replace the extension to `.js`.
  index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"),
},

3. Find modulethe comment example of the key above the plug section, and uncomment the following lines:

module: {
    
    
  rules: [
    {
    
     test: /\.(js|ts)x?$/, loader: "ts-loader" },
    {
    
     test: /\.css$/, use: ['style-loader','css-loader'] }
  ]
},

4. These settings enable your program to use ts-loaderthe compiler and import CSS files.

NOTE: If you want to add support for .scss or .sass files, you should install sass-loader:

npm install --save react react-dom

Then add this additional rule below the rule in webpack.config.jsthe :css-loader

module: {
    
    
  rules: [
    // ...
    {
    
    
      test: /\.s[ac]ss$/i,
      use: [
        // Creates `style` nodes from JS strings
        "style-loader",
        // Translates CSS into CommonJS
        "css-loader",
        // Compiles Sass to CSS
        "sass-loader",
      ],
    },
  ]
},

5. Save the changes and close webpack.config.jsthe file to continue.

6. Create a new file named in the root directory of the project tsconfig.json.

7. Open the file in a text editor tsconfig.json, then copy and paste the following into the file:

{
    
    
    "compilerOptions": {
    
    
      "target": "es2018",        /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
      "lib": ["ES2018", "DOM"],  /* Specify library files to be included in the compilation. */
      "allowJs": true,           /* Allow javascript files to be compiled. */
      "jsx": "react",            /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    },
    "include": ["src/**/*"],
}

8. Save the changes and close tsconfig.jsonthe file to continue.

Add a stylesheet to the project

A new cascading style sheet can now be created and added to the project.

1. Change to src/contacts _ assets/assetsthe directory.

2. Open the file in a text editor main.cssand delete the existing content.

3. Define some style attributes for the front end. For example, copy and paste the following styles into the file:

html {
    
    
    background-color: bisque;
}

body {
    
    
    font-family: Arial, Helvetica, sans-serif;
    display: block;
    margin: 10px;
}

h1 {
    
    
    color: darkblue;
    font-size: 32px;
}

div.new-entry {
    
    
    margin: 30px 20px 30px 20px;
}

.new-entry > div {
    
    
    margin-bottom: 15px;
}

table {
    
    
    margin-top: 12px;
    border-top: 1px solid darkblue;
    border-bottom: 1px solid darkblue;
}

#form {
    
    
    margin: 30px 0 30px 20px;
}

button {
    
    
    line-height: 20px;
}

#lookupName {
    
    
    margin-right: 12px;
}

4. Save the changes and close the main.css file, rename it to mycontacts.css to continue.

5. Change to src/contacts _ assets/srcthe directory.

cd ../src

6. Open the default file in a text editor index.jsand delete the existing content.

7. Copy and paste the following sample code into index.jsthe file:

import * as React from "react";
import { render } from "react-dom";
import { contacts } from "../../declarations/contacts";
import "../assets/mycontacts.css";

const Contact = () => {
  async function doInsert() {
    let name = document.getElementById("newEntryName").value;
    let add1 = document.getElementById("newEntryAddress1").value;
    let add2 = document.getElementById("newEntryAddress2").value;
    let email = document.getElementById("newEntryEmail").value;
    let phone = document.getElementById("newEntryPhone").value;
    contacts.insert(name, add1, add2, email, parseInt(phone, 10));
  }

  async function lookup() {
    let name = document.getElementById("lookupName").value;
    contacts.lookup(name).then((opt_entry) => {
      let entry;

      if (opt_entry.length == 0) {
        entry = { name: "", description: "", phone: "" };
      } else {
        entry = opt_entry[0];
      }

      document.getElementById("newEntryName").value = entry.name;
      document.getElementById("newEntryAddress1").value = entry.address1;
      document.getElementById("newEntryAddress2").value = entry.address2;
      document.getElementById("newEntryEmail").value = entry.email;
      document.getElementById("newEntryPhone").value = entry.phone.toString();
    });
  }

  return (
    <div className="new-entry">
      <h1>My Contacts</h1>
      <div>
        Add or update contact information:
        <form id="contact">
          <table>
            <tbody>
              <tr>
                <td>Name:</td>
                <td>
                  <input id="newEntryName"></input>
                </td>
              </tr>
              <tr>
                <td>Address 1 (street):</td>
                <td>
                  <input id="newEntryAddress1"></input>
                </td>
              </tr>
              <tr>
                <td>Address 2 (city and state):</td>
                <td>
                  <input id="newEntryAddress2"></input>
                </td>
              </tr>
              <tr>
                <td>Email:</td>
                <td>
                  <input id="newEntryEmail"></input>
                </td>
              </tr>
              <tr>
                <td>Phone:</td>
                <td>
                  <input id="newEntryPhone" type="number"></input>
                </td>
              </tr>
            </tbody>
          </table>
        </form>
      </div>
      <div>
        <button onClick={() => doInsert()}>Add Contact</button>
      </div>
      <div>
        Lookup name:{" "}
        <input id="lookupName" style={
   
   { lineHeight: "20px" }}></input>
        <button onClick={() => lookup()}>Lookup</button>
      </div>
    </div>
  );
};

document.title = "DFINITY CONTACT EXAMPLE";

render(<Contact />, document.getElementById("contacts"));

index.js8. Rename the modified file by running the following command index.jsx:

mv index.js index.jsx

9. Open the default src/contacts_assets/src/index.htmlfile in a text editor, delete main.cssthe link, and &lt;div id = "contacts" &gt; &lt;/div&gt;update the body content with .

For example:

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

10. Return to the root directory of the project directory.

start local network

Start the environment locally:

dfx start --background

Register, build and deploy dapps

To deploy dapps:

1. If necessary, check that you are still in the root directory of the project.

2. Register, build and deploy the dapp by running the following commands:

dfx deploy

To deploy jars on an Internet computer blockchain, you must specify that you are deploying to an Internet computer instead of your local environment, using the --network command line option:

dfx deploy --network=ic

PS: After deployment, you can directly access the front end through the principal of asset canister, for example: https://6neag-ryaaa-aaaai-qfikq-cai.raw.ic0.app

3. Start the Webpack development server:

npm start

view front end

1. Open your browser and navigate to <a href="http://localhost:8080">http://localhost:8080</a>. (or http://localhost: 8000

/?canisterId=${asset canister ID}或http://localhost:8080

/?canisterId=${asset canister ID})

NOTE
It should be noted that the listening port after dfx deploy is 8000, and the listening port after npm start is 8080. We can use localhost:8080 to directly access the front end of the project, but not localhost:8000. We need to add the parameter canisterId later (from this we can see the relationship between the two services opened by dfx start and npm start)

2. Verify that the content is correct, for example:

3. Create one or more test records by entering text in the Name, Address, and Email input fields and a number in the Phone input field, then click Add Contact.

4. Clear the form fields and type the contact name in the Lookup name field, then click Lookup to view the stored contact information.

Remember, the Lookup name you type must exactly match the name of the added contact.

Modify the stylesheet and test the changes

After reviewing the Contacts dapp, you may need to make some changes. To change stylesheet properties:

Open the file in a text editor src/contacts_assets/assets/mycontacts.cssand modify its style settings.

For example, you may wish to change the background color or style of an input form.

You should immediately see the update in an open browser window.

Modify front-end or back-end code

If you want to take it a step further, you might want to try modifying the front-end or back-end code for this tutorial. For example, you could try modifying the tutorial to do the following:

After adding a new contact (for example, as onClickpart of an event), change the front-end code to clear the input field.

Changed the Motoko program function to perform a partial match instead of an Nameexact string match on the field. (you'll need to run dfxdeploy to test your changes on your local environment)

Change the Motoko program to allow lookups based on different fields.

Stop the local canister execution environment

When you're done experimenting with a program, you can stop the local environment so it doesn't keep running in the background.

Stop the local development environment:

1. In a terminal showing the webpack dev server, press Control-C to interrupt the development server.

2. Run the following command to stop the Internet computer network:

dfx stop
logo

Guess you like

Origin blog.csdn.net/qq_29810031/article/details/123269271