React Hooks

@web3-onboard/react

Install

npm i @web3-onboard/react

Example Usage

1
import React from 'react'
2
import {
3
init,
4
useConnectWallet,
5
useSetChain,
6
useWallets
7
} from '@web3-onboard/react'
8
import injectedModule from '@web3-onboard/injected-wallets'
9
import trezorModule from '@web3-onboard/trezor'
10
import ledgerModule from '@web3-onboard/ledger'
11
import walletConnectModule from '@web3-onboard/walletconnect'
12
import walletLinkModule from '@web3-onboard/walletlink'
13
import portisModule from '@web3-onboard/portis'
14
import fortmaticModule from '@web3-onboard/fortmatic'
15
import torusModule from '@web3-onboard/torus'
16
import keepkeyModule from '@web3-onboard/keepkey'
17
18
const injected = injectedModule()
19
const walletLink = walletLinkModule()
20
const walletConnect = walletConnectModule()
21
22
const portis = portisModule({
23
apiKey: 'b2b7586f-2b1e-4c30-a7fb-c2d1533b153b'
24
})
25
26
const fortmatic = fortmaticModule({
27
apiKey: 'pk_test_886ADCAB855632AA'
28
})
29
30
const torus = torusModule()
31
const ledger = ledgerModule()
32
const keepkey = keepkeyModule()
33
34
const trezorOptions = {
35
36
appUrl: 'https://www.blocknative.com'
37
}
38
39
const trezor = trezorModule(trezorOptions)
40
41
const web3Onboard = init({
42
wallets: [
43
ledger,
44
trezor,
45
walletConnect,
46
keepkey,
47
walletLink,
48
injected,
49
fortmatic,
50
portis,
51
torus
52
],
53
chains: [
54
{
55
id: '0x1',
56
token: 'ETH',
57
label: 'Ethereum Mainnet',
58
rpcUrl: 'https://mainnet.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
59
},
60
{
61
id: '0x3',
62
token: 'tROP',
63
label: 'Ethereum Ropsten Testnet',
64
rpcUrl: 'https://ropsten.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
65
},
66
{
67
id: '0x4',
68
token: 'rETH',
69
label: 'Ethereum Rinkeby Testnet',
70
rpcUrl: 'https://rinkeby.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
71
},
72
{
73
id: '0x89',
74
token: 'MATIC',
75
label: 'Matic Mainnet',
76
rpcUrl: 'https://matic-mainnet.chainstacklabs.com'
77
}
78
],
79
appMetadata: {
80
name: 'Blocknative',
81
icon: '<svg><svg/>',
82
description: 'Demo app for Onboard V2',
83
recommendedInjectedWallets: [
84
{ name: 'MetaMask', url: 'https://metamask.io' },
85
{ name: 'Coinbase', url: 'https://wallet.coinbase.com/' }
86
]
87
}
88
})
89
90
function App() {
91
const [{ wallet, connecting }, connect, disconnect] = useConnectWallet()
92
const [{ chains, connectedChain, settingChain }, setChain] = useSetChain()
93
const connectedWallets = useWallets()
94
95
return (
96
<div>
97
<button onClick={() => connect()}>
98
{connecting ? 'connecting' : 'connect'}
99
</button>
100
{wallet && (
101
<div>
102
<label>Switch Chain</label>
103
{settingChain ? (
104
<span>Switching chain...</span>
105
) : (
106
<select
107
onChange={({ target: { value } }) =>
108
console.log('onChange called') || setChain({ chainId: value })
109
}
110
value={connectedChain.id}
111
>
112
{chains.map(({ id, label }) => {
113
return <option value={id}>{label}</option>
114
})}
115
</select>
116
)}
117
<button onClick={() => disconnect(wallet)}>
118
Disconnect Wallet
119
</button>
120
</div>
121
)}
122
123
{connectedWallets.map(({ label, accounts }) => {
124
return (
125
<div>
126
<div>{label}</div>
127
<div>Accounts: {JSON.stringify(accounts, null, 2)}</div>
128
</div>
129
)
130
})}
131
</div>
132
)
133
}
134
135
export default App
Copied!

init

The init function must be called before any hooks can be used. The init function just initializes web3-onboard and makes it available for all hooks to use. For reference check out the initialization docs for @web3-onboard/core

useConnectWallet

This hook allows you to connect the user's wallet and track the state of the connection status and the wallet that is connected.
1
import { useConnectWallet } from '@web3-onboard/react'
2
3
type UseConnectWallet = (): [
4
{ wallet: WalletState | null; connecting: boolean },
5
(options: ConnectOptions) => Promise<void>,
6
(wallet: DisconnectOptions) => Promise<void>
7
]
8
9
type ConnectOptions = {
10
autoSelect?: string // wallet name to autoselect for user
11
}
12
13
type DisconnectOptions = {
14
label: string // wallet label
15
}
16
17
type WalletState = {
18
label: string
19
icon: string
20
provider: EIP1193Provider
21
accounts: Account[]
22
chains: ConnectedChain[]
23
instance?: unknown
24
}
25
26
const [
27
{
28
wallet, // the wallet that has been connected or null if not yet connected
29
connecting // boolean indicating if connection is in progress
30
},
31
connect, // function to call to initiate user to connect wallet
32
disconnect // function to call to with wallet<DisconnectOptions> to disconnect wallet
33
] = useConnectWallet()
Copied!

useSetChain

This hook allows you to set the chain of a user's connected wallet, keep track of the current chain the user is connected to and the status of setting the chain. Passing in a wallet label will operate on that connected wallet, otherwise it will default to the last connected wallet.
1
import { useSetChain } from '@web3-onboard/react'
2
3
type UseSetChain = (
4
walletLabel?: string
5
): [
6
{
7
chains: Chain[]
8
connectedChain: ConnectedChain | null
9
settingChain: boolean
10
},
11
(options: SetChainOptions) => Promise<void>
12
]
13
14
type SetChainOptions = {
15
chainId: string
16
chainNamespace?: string
17
wallet?: WalletState['label']
18
}
19
20
const [
21
{
22
chains, // the list of chains that web3-onboard was initialized with
23
connectedChain, // the current chain the user's wallet is connected to
24
settingChain // boolean indicating if the chain is in the process of being set
25
},
26
setChain // function to call to initiate user to switch chains in their wallet
27
] = useSetChain()
Copied!

useWallets

This hook allows you to track the state of all the currently connected wallets.
1
import { useWallets } from '@web3-onboard/react'
2
3
type UseWallets = (): WalletState[]
4
5
const connectedWallets = useWallets()
Copied!

Build Environments

Many of the wallet modules require dependencies that are not normally included in browser builds (namely the node builtin modules such as crypto, buffer, util etc). If you are having build issues you can try the following bundler configs to resolve these dependency issues:

Webpack 4

Everything should just work since the node builtins are automatically bundled in v4

Webpack 5

You'll need to add some dev dependencies with the following command:
npm i --save-dev assert buffer crypto-browserify stream-http https-browserify os-browserify process stream-browserify util
Then add the following to your webpack.config.js file:
1
const webpack = require('webpack')
2
3
module.exports = {
4
resolve: {
5
alias: {
6
assert: 'assert',
7
buffer: 'buffer',
8
crypto: 'crypto-browserify',
9
http: 'stream-http',
10
https: 'https-browserify',
11
os: 'os-browserify/browser',
12
process: 'process/browser',
13
stream: 'stream-browserify',
14
util: 'util'
15
}
16
},
17
experiments: {
18
asyncWebAssembly: true
19
},
20
plugins: [
21
new webpack.ProvidePlugin({
22
process: 'process/browser',
23
Buffer: ['buffer', 'Buffer']
24
})
25
]
26
}
Copied!
If using create-react-app
CRACO provides an easy way to override webpack config which is obfuscated in Create React App built applications.
The above webpack 5 example can be used in the craco.config.js file at the root level in this case.
Last modified 1mo ago