Skip to content

Drop in solution for building single-page Ethereum dApps in React

License

Notifications You must be signed in to change notification settings

Pactum/web3-react

 
 

Repository files navigation

Web3 React

npm version Build Status Coverage Status

Web3 React is a drop in solution for building single-page Ethereum dApps in React. Yes, it uses Hooks!

Edit web3-react-demo

Example GIF

The marquee features of Web3 React are:

  • A robust management framework for the web3 object injected into browsers by MetaMask, Trust, etc. The framework exposes the current account, the current network ID, and an instantiated web3.js instance via a React Context.

  • A collection of React Hooks that can be used to display ETH and ERC20 balances, sign messages, and more.

  • A number of utility functions that format Etherscan links, convert token balances, and more.

  • A complete solution for sending transactions that abstracts away from common annoyances like estimating gas usage, setting a gas price, and checking for transaction errors.

Sample Implementations

Many of the patterns and APIs described below are shown in this CodeSandbox demo:

Edit web3-react-demo

Open a PR to include your Web3 React project here!

Quickstart

Install the npm package:

npm install web3-react

Web3 React exports 3 objects:

  1. Web3Provider (default export)
  • A Component wrapping the Web3Context Provider that ensure children can access the Web3Context. Web3Provider takes 5 optional props.
  1. Web3Consumer (named export)
  • A Component wrapping the Web3Context Consumer that enables children to access the Web3Context via a render prop. Web3Consumer takes 2 optional props.
  1. withWeb3 (named export)
  • This HOC gives passed Components access to the Web3Context via an injected web3 prop. withWeb3 takes 1 optional argument.

Using Web3 React: Starter Code

To take advantage of the Web3Context, Components must have a Web3Provider parent somewhere in their tree. It's recommended that the Web3Provider be placed at the top level of your app.

import React from 'react'
import ReactDOM from 'react-dom'
import Web3Provider from 'web3-react'

function App () {
  return (
    <Web3Provider>
      ...
    </Web3Provider>
  )
}

const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)

This ensures that your app will be able to access the Web3Context, which consists of:

{
  web3js: ...,
  account: ...,
  networkId: ...,
  reRenderers: {...}
}

Note: Web3 React guarantees that while the children of Web3Provider are rendered, none of the these context elements are null or undefined.

  1. web3js: A web3.js instance instantiated with the current web3 provider.
  2. account: The current active account.
  3. networkId: The current active network ID.
  4. reRenderers: Variables and functions to facilitate the re-rendering of data derived from account or networkId (such as a user's balance, which can change over time without their actual account changing). For how to use these reRenderers, see src/web3Hooks.js. useAccountEffect and useNetworkEffect convenience wrappers for useEffect are available as named exports of web3-react/hooks; they take care of re-renders automatically.
  • accountReRenderer: Forces re-renders of account-derived data.
  • forceAccountReRender: A function that triggers a global re-render for Hooks depending on accountReRenderer.
  • networkReRenderer: Forces re-renders of network-derived data.
  • forceNetworkReRender: A function that triggers a global re-render for Hooks depending on networkReRenderer.

Using Web3 React: Hooks - Recommended

The easiest way to use Web3 React is with Hooks! All Hooks exported by Web3 React are documented in docs/Hooks.md.

import React from 'react'
import { useWeb3Context, useAccountBalance } from 'web3-react/hooks'

function MyComponent () {
  const context = useWeb3Context()
  const balance = useAccountBalance()

  return (
    <>
      <p>{context.account}</p>
      <p>{balance}</p>
    </>
  )
}

Using Web3 React: Render Props - Conditionally Recommended

To access the Web3Context with a render prop, wrap Components in a Web3Consumer.

import React from 'react'
import Web3Provider, { Web3Consumer } from 'web3-react'

function AccountComponent (props) {
  const { account } = props
  return <p>{account}</p>
}

function MyComponent () {
  return (
    <Web3Consumer>
      {context =>
        <AccountComponent account={context.account} />
      }
    </Web3Consumer>
  )
}

Note: This pattern will work for arbitrarily deeply nested components. This means that the Web3Consumer doesn't necessarily need to be at the top level of your app. There also won't be performance concerns if you choose to use multiple Web3Consumers at different nesting levels.

Using Web3 React: HOCs - Not Recommended

If you really have to, you can give Components access to the Web3Context via a web3 prop by wrapping them with withWeb3.

import React from 'react'
import { withWeb3 } from 'web3-react'

function MyComponent (props) {
  const { web3 } = props
  const { account } = web3

  return <p>{account}</p>
}

const MyComponentWrapped = withWeb3(MyComponent)

Note: The high-level component which includes your Web3Provider Component cannot be wrapped with withWeb3.

Exhaustive Documentation

  • Documentation for the utility functions exported by Web3 React can be found separately in docs/Utilities.md.

  • Documentation for the Hooks exported by Web3 React can be found separately in docs/Hooks.md.

1. Web3Provider props

The Web3Provider Component takes 5 optional props:

  1. screens: React Components which will be displayed according to the web3 status of a user's browser. To see the default screens, play around with the CodeSandbox sample app or check out the implementation. Note that these screens are lazily loaded with React.lazy, and therefore are not SSR-compatible.
  • Initializing: Shown when Web3 React is being initialized. This screen is typically displayed only very briefly, or while requesting one-time account permission.

    • Default: The Component only appears after 1 second.
  • NoWeb3: Shown when no injected web3 variable is found.

    • Default: The Component encourages users to install MetaMask or download Trust.
  • PermissionNeeded: Shown when users deny your dApp permission to access their account. Denying access disables the entire dApp unless the accountRequired flag is set to false.

    • Default: The Component instructs users to grant your dApp access to their account.
  • UnlockNeeded: Shown when no account is available.

    • Default: The Component encourages users to unlock their wallet. This could possibly be combined with the PermissionNeeded Component (suggestions welcome).
  • UnsupportedNetwork: Shown when the user is on a network not in the supportedNetworks list. The list of supported network IDs is passed to this component in a supportedNetworkIds prop.

    • Default value: The Component encourages users to connect to any of the networks in the supportedNetworks list.
  • Web3Error: Shown whenever an error occurs in the polling process for account and network changes. The error is passed to this Component as an error prop.

    • Default: The Component displays the text of the passed error to the user.
  1. pollTime: The poll interval for account and network changes (in milliseconds). The current recommendation is to poll for account and network changes.
  • Default: 1000
  1. supportedNetworks: Enforces that the web3 instance is connected to a particular network. If the detected network ID is not in the passed list, the UnsupportedNetwork screen will be shown. Supported network IDs are: 1 (Mainnet), 3 (Ropsten), 4 (Rinkeby), and 42 (Kovan).
  • Default: [1, 3, 4, 42]
  1. accountRequired: If false, does not show the UnlockNeeded screen if a user does not expose any of their accounts.
  • Default: true
  1. children: React Components to be rendered upon successful Web3 React initialization.

2. Web3Consumer Props

  1. recreateOnNetworkChange. A flag that controls whether child components are freshly re-initialized upon network changes.
  • Default value: true
  1. recreateOnAccountChange. A flag that controls whether child components are freshly re-initialized upon account changes.
  • Default value: true

Re-initialization is often the desired behavior, though properly written Hooks should not require these flags to be set.

3. withWeb3 Arguments

Flags that can be passed in the second argument to withWeb3:

  1. recreateOnNetworkChange. See above.
  2. recreateOnAccountChange. See above.
withWeb3(..., { ... })

Notes

  • Prior art for Web3 React includes:

    • A pure Javascript implementation with some of the same goals: web3-webpacked.

    • A non-Hooks port of web3-webpacked to React that had some problems: web3-webpacked-react.

    • A React library with some of the same goals but that unfortunately uses the deprecated React Context API and does not use Hooks: react-web3.

  • Right now, Web3 React is opinionated in the sense that it relies on web3.js in lieu of possible alternatives like ethjs or ethers.js. In the future, it's possible that this restriction will be relaxed. It's not clear how this would best be achieved, however, so ideas and comments are welcome. Open an issue or PR!

About

Drop in solution for building single-page Ethereum dApps in React

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 96.7%
  • CSS 3.3%