Skip to content

Getting Started With React

Install

npm
npm install @happychain/react

Setup

After installing, the first thing you will need to do, is wrap your app in the HappyWalletProvider.

import React from 'react'
import ReactDOM from 'react-dom/client'
import { HappyWalletProvider } from '@happychain/react'
import App from './App.tsx'
 
ReactDOM.createRoot(document.getElementById('root')).render(
    <HappyWalletProvider>
        <App />
    </HappyWalletProvider> 
)

Usage

Web3 Integration

Next you will want to setup your web3 integration using the happyProvider. The HappyProvider is an EIP-1193 EVM provider. This means you can use it to initialize any standard web3 library as you normally would. The most common examples are below, but it should be fully compatible with most libraries.

Viem
import { happyProvider } from '@happychain/react' 
import { createPublicClient, createWalletClient, custom } from "viem"
 
const transport = custom(happyProvider) 
const publicClient = createPublicClient({ transport }) 
const walletClient = createWalletClient({ transport }) 

Getting the Active User

The useHappyChain hook returns the current user as a HappyUser if the user is connected, otherwise it returns undefined.

import React from 'react'
import { useHappyChain } from '@happychain/react'
 
function UserAddressComponent() {
    const { user } = useHappyChain()
 
    if (!user) {
        return <div>Not connected</div>
    }
 
    return <div>{user.address}</div>
}

Getting the Active User from Outside of React Components

User changes, such as when a user logs in or out, can be subscribed to the onUserUpdate listener. If the user is undefined, then they are not currently logged in have or have logged out. If the user is a HappyUser then it will be populated with all their shared info, such as wallet address and name.

import { onUserUpdate } from '@happychain/react'
 
onUserUpdate((user) => {
    console.log("HappyChain User:", user)
})

Alternatively, the current user Is always exposed via the getCurrentUser call.

import { getCurrentUser } from '@happychain/react'
 
const user = getCurrentUser()
console.log("HappyChain User:", user)

onUserUpdate only fires whenever the user changes, so if you want to have something depend on the current user, you should write your code as follows:

import { type HappyUser, getCurrentUser, onUserUpdate } from '@happychain/react'
 
const doSomethingWithUser = (user?: HappyUser) => {
    console.log("HappyChain User:", user)
}
 
doSomethingWithUser(getCurrentUser())
onUserUpdate(doSomethingWithUser)