Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

web3-react

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

web3-react

Drop in solution for building Ethereum dApps in React.

  • 2.0.12
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
54
decreased by-85.97%
Maintainers
1
Weekly downloads
 
Created
Source

npm version Build Status Coverage Status

Example GIF

Resources

  • Documentation for web3-react is available on Gitbook.

  • A live demo of web3-react is available on CodeSandbox.

Introduction

web3-react is a drop-in solution for building Ethereum dApps in React. Its marquee features are:

  • Robust support for commonly used web3 providers such as MetaMask, WalletConnect, Infura, Trust, and more.

  • A robust framework which exposes an ethers.js or web3.js instance, the current account and network id, and a variety of helper functions to your dApp via a React Context.

  • The ability to write fully featured, custom Connectors to manage every aspect of your dApps connectivity with the Ethereum blockchain and user account(s), if you need it.

Implementations

Projects using web3-react include:

Open a PR to add your project to the list! If you're interested in contributing, check out Contributing-Guidelines.md.

Quickstart

If you want to cut straight to the chase, check out the CodeSandbox demo!

Edit web3-react-demo

1. Install

Ensure you have an up-to-date react and react-dom version:

yarn add react@latest react-dom@latest

Then, get the npm package:

yarn add web3-react@unstable

2. Setup Connectors

Now, decide how you want users to interact with your dApp. For the vast majority of dApps, this will be with some combination of MetaMask/Infura/WalletConnect. For more details see Connectors.md.

import { MetaMaskConnector, InfuraConnector, WalletConnectConnector } from 'web3-react/connectors'

const connectors = {
  metamask: new MetaMaskConnector(),
  infura: new InfuraConnector({ providerURL: 'https://mainnet.infura.io/v3/<YOUR-API-KEY>' }),
  walletConnect: new WalletConnectConnector({
    bridge: 'https://bridge.walletconnect.org',
    supportedNetworkURLs: { 1: 'https://mainnet.infura.io/v3/<YOUR-API-KEY>' },
    defaultNetwork: 1
  })
}

3. Setup Web3Provider

The next step is to setup a Web3Provider at the root of your dApp. This ensures that children components are able to take advantage of the web3-react context variables.

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

export default function App () {
  return (
    <Web3Provider
      connectors={...}
      libraryName={...}
      reRendererNames={...}
    >
      ...
    </Web3Provider>
  )
}

Web3Provider takes 4 props:

  1. connectors (required): An object mapping connector names to Connectors (see the previous section).

  2. libraryName (optional): web3.js or ethers.js, depending on which library you wish to use in your dApp.

  3. reRendererNames (optional) strings which with you wish to control specific re-renders of data after, e.g. a transaction confirmation.

  4. children (required): The rest of your dApp.

4. Using web3-react

Finally, you're ready to use web3-react!

The easiest way to use web3-react is with Hooks.

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

function MyComponent() {
  const context = useWeb3Context()

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

For more details see Hooks.md.

To use web3-react with render props, wrap Components in a Web3Consumer. It takes two props:

  1. recreateOnNetworkChange (optional, default true). A flag that controls whether child components are freshly re-initialized upon network changes.

  2. recreateOnAccountChange (optional, default true). A flag that controls whether child components are freshly re-initialized upon account changes.

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

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

function AccountComponent({ account }) {
  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.

If you must, you use web3-react with an HOC. The withWeb3 wrapper's second argument can optionally be the recreate flags from the render props pattern.

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

function MyComponent({ web3 }) {
  const { account } = web3
  return <p>{account}</p>
}

export default withWeb3(MyComponent)

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

Context

Regardless of how you inject the context, it looks like:

{
  active: boolean
  connectorName?: string
  library?: Library
  networkId?: number
  account?: string | null
  error: Error | null

  setConnector: Function
  setFirstValidConnector: Function
  unsetConnector: Function

  reRenderers: IReRendererState
  forceReRender: Function
}

Variables

  • active: A flag for whether web3-react has been initialized.
  • connectorName: The name of the currently active connector
  • library: A web3.js or ethers.js instance instantiated with the current web3 provider.
  • networkId: The current active network ID.
  • account: The current active account.
  • error: A global error if one exists.

Manager Functions

  • setConnector(connectorName): Activates a connector.
  • setFirstValidConnector(connectorName): Tries to activate each connector in turn.
  • unsetConnector(): Resets the currently active connector.

Renderers

These variables/functions facilitate the re-rendering of specific data. For example, a user's balance can change over time.

import { useEffect } from 'react'
import { useWeb3Context } from 'web3-react/hooks'

const reRendererNames = ['MyReRenderer']
// assume this array was passed to the Web3Provider...

function MyComponent() {
  const context = useWeb3Context()

  useEffect(() => {
    // run code here that should run again when calling context.forceReRender('MyReRenderer')
  }, [context.reRenderers.MyReRenderer])

  ...
}
  • reRenderers: An object, where the keys are the reRendererNames passed into the Web3Provider and the values force re-renders of specific data when included in useEffect hook updaters.
  • forceReRender(reRendererName): A function that triggers a global re-render of the reRendererName.

Utility Functions

Documentation for the utility functions exported by web3-react can be found in Utilities.md.

Hooks

Documentation for the hooks exported by web3-react can be found in Hooks.md.

Notes

Prior art for web3-react includes:

Keywords

FAQs

Package last updated on 11 Feb 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc