Connecting your Solana Program to a React Application

We can use @solana/web3.js to connect our smart contract to a frontend React application. You'll need to deploy your contract and get the ABI in order to use it.

  1. Install the necessary dependencies:

npm install @solana/web3.js
  1. Import the Solana Web3.js library in your React component:

codeimport SolanaWeb3 from "@solana/web3.js";
  1. Initialize the Solana Web3.js object with a connection to a Solana cluster:

codeconst solana = new SolanaWeb3(<solana-cluster-url>);
  1. Load the ABI for your smart contract:

jcodeconst abi = <abi-for-your-smart-contract>;
  1. Create a contract object:

codeconst contract = new solana. Contract(<contract-address>, abi);
  1. Call functions on the contract:

codecontract.methods.<function-name>().call().then((result) => {
    console.log(result);
});
  1. You can also send transactions to the contract:

codecontract.methods.<function-name>().send({
    from: <sender-address>,
    value: <amount-of-token>,
    gas: <gas-limit>,
    gasPrice: <gas-price>,
}).then((receipt) => {
    console.log(receipt);
});

Here's an example React component connected to a "Hello World" Solana contract:

import React, { useState, useEffect } from "react";
import SolanaWeb3 from "@solana/web3.js";

const HelloWorld = () => {
  const [message, setMessage] = useState("");

  useEffect(() => {
    const solana = new SolanaWeb3("<solana-cluster-url>");

    const abi = [
      {
        constant: true,
        inputs: [],
        name: "getMessage",
        outputs: [
          {
            name: "",
            type: "string"
          }
        ],
        payable: false,
        stateMutability: "view",
        type: "function"
      }
    ];

    const contract = new solana.Contract(
      "<contract-address>",
      abi
    );

    contract.methods
      .getMessage()
      .call()
      .then(result => {
        setMessage(result);
      });
  }, []);

  return <div>Hello World: {message}</div>;
};

export default HelloWorld;

Last updated