TON Connect for React
Recommended SDK for React Apps is a UI React SDK. It is a React component that provides a high-level way to interact with TON Connect.
Implementation
1) Installation
To start integrating TON Connect into your DApp, you need to install the @tonconnect/ui-react
package. You can use npm or yarn for this purpose:
- npm
- Yarn
- pnpm
npm i @tonconnect/ui-react
yarn add @tonconnect/ui-react
pnpm add @tonconnect/ui-react
2) TON Connect Initiation
After installing the package, you should create a manifest.json
file for your application. More information on how to create a manifest.json file can be found here.
After creating the manifest file, import TonConnectUIProvider to the root of your Mini App and pass the manifest URL:
import { TonConnectUIProvider } from '@tonconnect/ui-react';
export function App() {
return (
<TonConnectUIProvider manifestUrl="https://<YOUR_APP_URL>/tonconnect-manifest.json">
{ /* Your app */ }
</TonConnectUIProvider>
);
}
3) Connect to the Wallet
Add the TonConnectButton
. The TonConnect Button is a universal UI component for initializing a connection. After the wallet is connected, it transforms into a wallet menu. It is recommended to place it in the top right corner of your app.
export const Header = () => {
return (
<header>
<span>My App with React UI</span>
<TonConnectButton />
</header>
);
};
You can add className and style props to the button as well. Note that you cannot pass child to the TonConnectButton:
<TonConnectButton className="my-button-class" style={{ float: "right" }}/>
Moreover, you always can initiate the connection manually, using useTonConnectUI
hook and connectWallet method.
4) Redirects
If you want to redirect user to a specific page after wallet connection, you can use useTonConnectUI
hook and customize your return strategy.
Telegram Mini Apps
If you want to redirect user to a Telegram Mini App after wallet connection, you can customize the TonConnectUIProvider
element:
<TonConnectUIProvider
// ... other parameters
actionsConfiguration={{
twaReturnUrl: 'https://t.me/<YOUR_APP_NAME>'
}}
>
</TonConnectUIProvider>
5) UI customization
To customize UI of the modal you can use useTonConnectUI
hook and setOptions
function. See more about useTonConnectUI hook in Hooks section.
Hooks
If you want to use some low-level TON Connect UI SDK features in your React app, you can use hooks from @tonconnect/ui-react
package.
useTonAddress
Use it to get user's current ton wallet address. Pass boolean parameter isUserFriendly to choose format of the address. If wallet is not connected hook will return empty string.
import { useTonAddress } from '@tonconnect/ui-react';
export const Address = () => {
const userFriendlyAddress = useTonAddress();
const rawAddress = useTonAddress(false);
return (
userFriendlyAddress && (
<div>
<span>User-friendly address: {userFriendlyAddress}</span>
<span>Raw address: {rawAddress}</span>
</div>
)
);
};
useTonWallet
Use it to get user's current ton wallet. If wallet is not connected hook will return null.
See all wallet's properties
Wallet interface WalletInfo interface
import { useTonWallet } from '@tonconnect/ui-react';
export const Wallet = () => {
const wallet = useTonWallet();
return (
wallet && (
<div>
<span>Connected wallet: {wallet.name}</span>
<span>Device: {wallet.device.appName}</span>
</div>
)
);
};
useTonConnectUI
Use it to get access to the TonConnectUI
instance and UI options updating function.
See more about TonConnectUI instance methods
See more about setOptions function
import { Locales, useTonConnectUI } from '@tonconnect/ui-react';
export const Settings = () => {
const [tonConnectUI, setOptions] = useTonConnectUI();
const onLanguageChange = (lang: string) => {
setOptions({ language: lang as Locales });
};
return (
<div>
<button onClick={() => tonConnectUI.sendTransaction(myTransaction)}>
Send transaction
</button>
<div>
<label>language</label>
<select onChange={e => onLanguageChange(e.target.value)}>
<option value="en">en</option>
<option value="ru">ru</option>
</select>
</div>
</div>
);
};
useIsConnectionRestored
Indicates current status of the connection restoring process. You can use it to detect when connection restoring process if finished.
import { useIsConnectionRestored } from '@tonconnect/ui-react';
export const EntrypointPage = () => {
const connectionRestored = useIsConnectionRestored();
if (!connectionRestored) {
return <Loader>Please wait...</Loader>;
}
return <MainPage />;
};
Usage
Let's take a look at how to use the React UI SDK on practice.
Sending transactions
Send TON coins (in nanotons) to a specific address:
import { useTonConnectUI } from '@tonconnect/ui-react';
const transaction = {
messages: [
{
address: "0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F", // destination address
amount: "20000000" //Toncoin in nanotons
}
]
}
export const Settings = () => {
const [tonConnectUI, setOptions] = useTonConnectUI();
return (
<div>
<button onClick={() => tonConnectUI.sendTransaction(transaction)}>
Send transaction
</button>
</div>
);
};
- Get more examples here: Preparing Messages
Understanding Transaction Status by Hash
The principle located in Payment Processing (using tonweb). See more
Optional Check (ton_proof) on the Backend
Understand how to sign and verify messages: Signing and Verification
Use tonConnectUI.setConnectRequestParameters
function to pass your connect request parameters.
This function takes one parameter:
Set state to 'loading' while you are waiting for the response from your backend. If user opens connect wallet modal at this moment, he will see a loader.
const [tonConnectUI] = useTonConnectUI();
tonConnectUI.setConnectRequestParameters({
state: 'loading'
});
or
Set state to 'ready' and define tonProof
value. Passed parameter will be applied to the connect request (QR and universal link).
const [tonConnectUI] = useTonConnectUI();
tonConnectUI.setConnectRequestParameters({
state: 'ready',
value: {
tonProof: '<your-proof-payload>'
}
});
or
Remove loader if it was enabled via state: 'loading'
(e.g. you received an error instead of a response from your backend). Connect request will be created without any additional parameters.
const [tonConnectUI] = useTonConnectUI();
tonConnectUI.setConnectRequestParameters(null);
You can call tonConnectUI.setConnectRequestParameters
multiple times if your tonProof payload has bounded lifetime (e.g. you can refresh connect request parameters every 10 minutes).
const [tonConnectUI] = useTonConnectUI();
// enable ui loader
tonConnectUI.setConnectRequestParameters({ state: 'loading' });
// fetch you tonProofPayload from the backend
const tonProofPayload: string | null = await fetchTonProofPayloadFromBackend();
if (!tonProofPayload) {
// remove loader, connect request will be without any additional parameters
tonConnectUI.setConnectRequestParameters(null);
} else {
// add tonProof to the connect request
tonConnectUI.setConnectRequestParameters({
state: "ready",
value: { tonProof: tonProofPayload }
});
}
You can find ton_proof
result in the wallet
object when wallet will be connected:
import {useTonConnectUI} from "@tonconnect/ui-react";
const [tonConnectUI] = useTonConnectUI();
useEffect(() =>
tonConnectUI.onStatusChange(wallet => {
if (wallet.connectItems?.tonProof && 'proof' in wallet.connectItems.tonProof) {
checkProofInYourBackend(wallet.connectItems.tonProof.proof, wallet.account);
}
}), []);
Wallet Disconnection
Call to disconnect the wallet:
import { useTonConnectUI } from '@tonconnect/ui-react';
const [tonConnectUI] = useTonConnectUI();
await tonConnectUI.disconnect();
API Documentation
Examples
- Step-by-step TON Hello World guide to create a simple DAppwith React UI.
- Demo dApp - Example of a DAppwith
@tonconnect/ui-react
. - ton.vote - Example of React website with TON Connect implementation.