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.
Install the necessary dependencies:
npm install @solana/web3.js
Import the Solana Web3.js library in your React component:
codeimport SolanaWeb3 from "@solana/web3.js";
Initialize the Solana Web3.js object with a connection to a Solana cluster:
codeconst solana = new SolanaWeb3(<solana-cluster-url>);
Load the ABI for your smart contract:
jcodeconst abi = <abi-for-your-smart-contract>;
Create a contract object:
codeconst contract = new solana. Contract(<contract-address>, abi);
Call functions on the contract:
codecontract.methods.<function-name>().call().then((result) => {
console.log(result);
});
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;
PreviousAssignment: Ship your own Anchor ApplicationNextAssignment: Create a currency on Solana using Rust
Last updated