skip to Main Content

i am currently learning motoko for my backend. I just want to know how to connect my react framework with motoko? i searched the docs already but cant seem to find the answer

still im currently looking a way to connect my react framework. at the moment im using the basic dfx new tags to create. but im more familiar with react as my frontend

2

Answers


  1. It is not possible to directly use React within Motoko code as they are different programming languages.
    However, you can create a separate React frontend for your Motoko backend. Set up your backend in Motoko, define an API, and make HTTP requests or use the IC Canister SDK in your React components to communicate with the backend.

    This way, you can connect your React frontend with your Motoko backend and utilize React for your frontend development while leveraging Motoko for the backend logic.

    Login or Signup to reply.
  2. It sounds like you are in addition to deploying a Motoko backend canister, also using ICP and dfx to host the frontend using that Motoko backend canister. In other words, as if they are part of the same project like you ran dfx new awesomeproject. If that’s the case it’ll be easier, since you can use dfx to generate the declarations of your Motoko backend you’ll use to create an instance of it in your frontend.

    Usually it goes something like:

    dfx deploy; #creates, builds and installs all the canisters in dfx.json
    dfx generate; #note you need to call this to use your Motoko in the frontend. 
    

    While there’s more involved ways to create the Motoko canister instance (like when you want to use authentication), when you do run dfx generate and have your bundler (webpack, craco, vite, etc) setup correctly, it should make it possible to import the Motoko canister directly into your frontend:

    import { backend } from './declarations/backend';
    
    document.getElementById("call-Motoko-backend-button").click += async {
      const response = await backend();
      // do something with response...
    }
    
    // frontend code
    

    I personally recommend using/learning Vite, as ESM makes a lot of things much simpler.

    Here’s some resources (note to lurking moderators, these are specifically hand picked) to get you going:

    Build a Web3 App With React Js

    Vite React Motoko Starter Template

    Internet Identity – AuthClient React Demo

    Build a Web3 Dapp with Next.js and Motoko

    The author of the Vite-React-Motoko-Starter also made it possible to run Motoko directly in node:

    Codesandbox with React + Motoko literally in the frontend

    Invoice Canister with React Frontend Sample App

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search