
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?
- Import or copy paste useChain snippet from here
- Search for your chain Params at https://chainid.network/chains.json and pass it to `CHAINOBJECT`
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.