├── README.md
├── metamask-auth.js
└── metamask-auth.module.css
/README.md:
--------------------------------------------------------------------------------
1 | ## MetaMask React Auth Component
2 |
3 |
4 |
5 | ### Works on desktop and mobile!
6 |
7 |
8 |
9 |
10 |
11 | Just change your `dappUrl` in `metamask-auth.jsx`.
12 |
13 | Demo: [metamask-auth.ilamanov.repl.co](https://metamask-auth.ilamanov.repl.co/)
14 | Demo code: [replit.com/@ilamanov/metamask-auth](https://replit.com/@ilamanov/metamask-auth?v=1)
15 |
16 | Code walkthrough: [Build a React Component For MetaMask Auth](https://betterprogramming.pub/build-a-react-component-for-metamask-auth-10b7ecba5c3f)
17 |
--------------------------------------------------------------------------------
/metamask-auth.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import styles from "./metamask-auth.module.css";
3 |
4 | function isMobileDevice() {
5 | return 'ontouchstart' in window || 'onmsgesturechange' in window;
6 | }
7 |
8 | async function connect(onConnected) {
9 | if (!window.ethereum) {
10 | alert("Get MetaMask!");
11 | return;
12 | }
13 |
14 | const accounts = await window.ethereum.request({
15 | method: "eth_requestAccounts",
16 | });
17 |
18 | onConnected(accounts[0]);
19 | }
20 |
21 | async function checkIfWalletIsConnected(onConnected) {
22 | if (window.ethereum) {
23 | const accounts = await window.ethereum.request({
24 | method: "eth_accounts",
25 | });
26 |
27 | if (accounts.length > 0) {
28 | const account = accounts[0];
29 | onConnected(account);
30 | return;
31 | }
32 |
33 | if (isMobileDevice()) {
34 | await connect(onConnected);
35 | }
36 | }
37 | }
38 |
39 |
40 | export default function MetaMaskAuth({ onAddressChanged }) {
41 | const [userAddress, setUserAddress] = useState("");
42 |
43 | useEffect(() => {
44 | checkIfWalletIsConnected(setUserAddress);
45 | }, []);
46 |
47 | useEffect(() => {
48 | onAddressChanged(userAddress);
49 | }, [userAddress]);
50 |
51 | return userAddress ? (
52 |