I'm building a React dapp and I want to allow my users to connect their Phantom wallets to it. The wallet adapter maintained by Solana does everything I need, but all the examples and docs assume that I want to use their UI component for the connect button. I want a button that I can style how I want that immediately attempts to connect to Phantom instead of prompting the user with what wallet type they want. I see a connect
function in the useWallet
hook but can't figure out how to use it (the disconnect
function works fine) — how can I create my own component for this?
2 Answers
You can follow the simple approach mentioned below for Phantom wallet, if you don't want to use the wallet adapter package.
// to do transactions using the selected wallet you can expose a onWalletConnect prop, that return the selectedWallet
function PhantomWallet (onWalletConnect) {
const [selectedWallet, setSelectedWallet] = useState(undefined);
const [isConnected, setConnected] = useState(false);
useEffect(() => {
if (selectedWallet) {
selectedWallet.connect();
selectedWallet.on('connect', () => {
setConnected(true);
console.log('Connected to wallet ' + selectedWallet.publicKey.toBase58());
console.log('selected wallet', selectedWallet);
onWalletConnect(selectedWallet);
});
selectedWallet.on('disconnect', () => {
setConnected(false);
console.log('Disconnected from wallet');
});
return () => {
selectedWallet.disconnect();
};
}
}, [selectedWallet]);
const handleButtonClick = () => {
if (window.solana) { // when the Phantom extension is installed, solana is set on window
setSelectedWallet(window.solana);
} else {
console.log('Phantom not available, get it from here, https://phantom.app/');
}
}
// you can render the connect button conditionally based on isConnected state
return (
<button onClick={handleButtonClick}>
<img src={phantomIcon}></img>
<span>Connect using Phantom</span>
</button>);
connect
to work and how it has failed