Mint Club
Search…
Connect Wallet (React.js)
Useful code snippets for wallet implementation on React.js
For a complete example, check Code Sandbox.

1. Installing dependencies

First, install necessary dependencies for your react project.
1
yarn add @web3-react/core ethers
Copied!

2. Setting up @web-react Root Provider

Edit your App.js file.
1
import { Web3ReactProvider } from '@web3-react/core';
2
import { BrowserRouter as Router } from 'react-router-dom';
3
import { ethers } from 'ethers';
4
import Routes from 'routes'; // your custom Routes.js file
5
6
const POLLING_INTERVAL = 12000;
7
8
const getLibrary = (provider) => {
9
const library = new ethers.providers.Web3Provider(provider);
10
library.pollingInterval = POLLING_INTERVAL;
11
return library;
12
};
13
14
function App() {
15
return (
16
<Web3ReactProvider getLibrary={getLibrary}>
17
<Router>
18
<Routes />
19
</Router>
20
</Web3ReactProvider>
21
);
22
}
23
24
export default App;
Copied!

3. Setting up Connectors

Implement connectors based on which wallet you're going to provide.
1
import { InjectedConnector } from '@web3-react/injected-connector'
2
3
// Other possible connectors
4
// import { WalletConnectConnector } from '@web3-react/walletconnect-connector';
5
// import { WalletLinkConnector } from '@web3-react/walletlink-connector';
6
// import { LedgerConnector } from '@web3-react/ledger-connector';
7
// import { BscConnector } from '@binance-chain/bsc-connector';
8
9
export const injected = new InjectedConnector({
10
supportedChainIds: [1, 3, 4, 5, 42, 56, 97, 1337],
11
});
12
13
// refer to https://github.com/NoahZinsmeister/web3-react
14
// for all available connectors
Copied!

4. Basic wallet login / logout

1
import { useWeb3React } from '@web3-react/core'
2
import { injected } from '[YOUR CONNECTOR PATH]'
3
4
function SomeComponent() {
5
const { activate, deactivate, account } = useWeb3React();
6
7
return (
8
<div>
9
Account: {account}
10
{account
11
? <button onClick={() => deactivate()}>Disconnect</button>
12
: <button onClick={() => activate(injected)}>Connect</button>
13
}
14
</div>
15
);
16
}
Copied!
Last modified 1mo ago