Disconnect MetaMask from a React dApp

Ryan Harris
InstructorRyan Harris
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Users should also be given the option to disconnect their wallet from your dApp.

There isn’t a programatic way to accomplish this, but we can remove their wallet address from state, adjust the UI, and use react-router to navigate them to root in order to provide a clear UX.

Instructor: [0:00] Let's add a new button so users can disconnect their metamask wallet from our application. First, we're going to come into our connect component. Below connectWallet(), we'll add a new function, constDisconnectWallet().

[0:14] Unlike the function above, there's no programmatic way to disconnect our wallet. We're going to simulate a UX scene in many other DApps. Let's go up to our app component and come down to our connect component here.

[0:27] We're going to add another prop and we'll call it onDisconnect. OnDisconnect =. This will be a function. We want to set the address in our local state back to null. We'll say, set address = null.

[0:44] If we go back to connect, we can add the new prop onDisconnect, come down to the disconnectWallet() function below, and call onDisconnect. As a nice-to-have, we're also going to come to the top of the file and import useNavigate from React Router. We'll do import { useNavigate } from 'react-router-dom'. Then in our component, const navigate = useNavigate, which will allow us to reroute users.

[1:18] If we come back down to the disconnect function, after we disconnect the wallet, let's also navigate the user home by saying navigate home. Lastly, we should update our UI state to reflect whether or not a wallet is connected.

[1:33] Come down below. First, let's hide the connect button if a wallet is already connected. We only want to show this if we do not have an address coming in as a prop. In its place, let's render some new markup. When we have an address, a user sees an indication they're connected.

[2:00] Here, we'll show a common shorthand for wallet addresses. The first six characters, and then the last four. Outside of this box here, we'll want to conditionally render our disconnect button. We'll say, if we have an address, meaning we're connected, let's render a new box.

[2:18] Inside of it, we'll have a disconnect button and set its onClick callback to be the disconnect wallet function we added earlier. OnClick = disconnectWallet.

[2:32] If we come to the browser and if we click Connect, say yes, you can see we now have our wallet address being displayed and a Disconnect button. If we click Disconnect, we now see the Connect button.

[2:47] To review, we added an onDisconnect prop to our connect component, which resets the address value in our component state and simulates a disconnected wallet.