4

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?

1
  • consider adding some example code and more explicitly describing what you've attempted to get connect to work and how it has failed
    – trent.sol
    Jul 21, 2022 at 18:42

2 Answers 2

3

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>);

  
0
3

The wallet adapter is split into the core and UI packages.

If you want to create your own UI you can create a wrapper over the core package similarly to how the UI package works.

You can fork the UI package and tweak it to your desired style and functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.