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:

Last updated