React Hook for DApps | Switching Network Chains in Metamask.

Cut Outs
1 min readNov 16, 2021

--

If you’re building your DApp on a different chain like polygon or Sol or Avalanche. One of the most frustrating thing for user experience is manually adding chain or switching chain on meta-mask.

what we want to do or achieve?

With a click of button, let your users switch chain directly in your DApp like how https://chainlist.org does.

How to?

const CHAINOBJECT; 
const { chainId, switchChain } = useChain();
  • check if your user is on the Right Chain.
const checkIfOnChain = () => {
return chainId === CHAINOBJECT.chainId;
}
  • change chain if user clicks a button.
const handleSwitchChainClick = (event) => {
switchChain(CHAINOBJECT)
.then(() => {
console.log(chainId);
})
.catch((err) => {
console.log(err);
})
}

Thats it, with 3 steps you would be able to give your user a smooth experience.

If you want a live demonstation — https://ballooncoins.netlify.app/

The following snippet belongs to one of the many useful react-hooks for DApp developers. To contribute or explore more check here on github.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Cut Outs
Cut Outs

Written by Cut Outs

The NFT filter in digital world.

No responses yet

Write a response