Coder Social home page Coder Social logo

react-web3's Introduction

React Web3

demo

Ensure web3 is available before your app loads.

This package is compatible with both [email protected] and [email protected]

react-web3 exports a <Web3Provider /> React component which wraps your app and ensures it doesn't render until web3 is available. It also renders a nice message to the user to guide them in the following cases:

  1. The user is not using a web3-capable browser, or
  2. The user has web3 support, but their account is locked (their ETH address is inaccessible)

Along with the above, <Web3Provider /> also:

  • Reacts to the user unlocking their wallet or switching accounts.
  • Provides a context to your entire app with useful data.
  • Accepts a callback that is called when user switches to a different account.

Installation

$ npm install react-web3

Test

$ npm test

Usage

Wrap your root-level react component:

import { Web3Provider } from 'react-web3';

// ...

// Ensure that <App /> doesn't render until we confirm web3 is available
ReactDOM.render(rootEl,
  <Web3Provider>
    <App />
  </Web3Provider>
);

Context

<Web3Provider /> provides a child context to your app with useful data:

import React from 'react';
import PropTypes from 'prop-types';

function SomeComponent(props, context) {
  const web3Context = context.web3;

  /**
   * web3Context = {
   *   accounts: {Array<string>} - All accounts
   *   selectedAccount: {string} - Default ETH account address (coinbase)
   *   network: {string} - One of 'MAINNET', 'ROPSTEN', or 'UNKNOWN'
   *   networkId: {string} - The network ID (e.g. '1' for main net)
   * }
   */

  return (
    <div>
      Hello Web3
    </div>
  );
}

SomeComponent.contextTypes = {
  web3: PropTypes.object
};

export default SomeComponent;

Accepted Props

<Web3Provider /> accepts the following optional props:

  • onChangeAccount (Function): Callback which is called when the user switches to a new account. Callback will receive the new ETH address as an argument.
    • Example: onChangeAccount={nextAddress => console.log(nextAddress)}
  • web3UnavailableScreen (ReactElement): React component to override the screen that is shown when web3 is unavailable.
    • Example: web3UnavailableScreen={() => <div>You need web3!</div>}
  • accountUnavailableScreen (ReactElement): React component to override the screen that is shown when the user's wallet is locked.
    • Example: accountUnavailableScreen={() => <div>Please unlock your wallet!</div>}
  • passive (Boolean): If true, your app will be rendered right away even if an ETH address is not available, and the message screens will become irrelevant and never be rendered. This is useful for apps that don't require web3 in order to render the app, but which has optional features that require web3. An example would be if you had an online store that simply allowed ETH as a payment option. In this case, you could read the web3 context and handle it manually in any of your components.
    • Example:
      const methods = ['Credit Card', 'Check', 'Ether'];
      const PaymentMethods = (props, context) => (
        <div>
          {methods.filter(
            // filter out the 'Ether' option if no account is available
            method => method !== 'Ether' || !!context.web3.selectedAccount
          ).map(
            method => <PaymentMethod method={method} key={method} />
          )}
        </div>
      )

Redux Support

If you're using react-redux, then you most likely have a <Provider /> component at the very root of your app. If this is the case, <Web3Provider /> will dispatch the following actions to your redux store:

  • web3/RECEIVE_ACCOUNT: Dispatched the first time an ETH account is available.
  • web3/CHANGE_ACCOUNT: Dispatched when the user switches between accounts.
  • web3/LOGOUT: Dispatched when user logs out (accounts are no longer available).

Both actions provide the ETH address at action.address;

Example Usage:

// In your reducer:
function reducer(state, action) {
  switch(action.type) {
    case 'web3/RECEIVE_ACCOUNT':
      return {
        ...state,
        ethAddress: action.address
      };

    case 'web3/CHANGE_ACCOUNT':
      return {
        ...state,
        ethAddress: action.address
      };
    case 'web3/LOGOUT':
      return {
        ...state,
        ethAddress: null
      }
  }
}

react-web3's People

Contributors

coopermaruyama avatar danfinlay avatar ewingrj avatar gtaschuk avatar guix77 avatar jahosh avatar kaibakker avatar rymnc avatar tylerdiaz avatar vincentserpoul avatar wanderingstan avatar wayne5540 avatar youfoundron avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-web3's Issues

Chrome problems with Metamask

Hi,

Thanks for this!

My question is maybe a bit off-topic, sorry if it is. I'm using a window.addEventListener callback in componentDidMount() to load data from the BC. With Chrome and Metamask, most of the time data won't load. When I turn on Developer tools with caching disabled, everything is fine. I don't have such problems with Firefox. The App was created with create-react-app.

Does someone have any clue ? I was thinking it could be related to https://stackoverflow.com/questions/44436179/better-pattern-to-detect-web3-default-account-when-using-metamask and that maybe a timeout could help, but I did not try yet.

Make provider agnostic

Hey dude, great stuff. I'm planning on integrating a similar pattern for EthJS: https://github.com/ethjs

Would you be able to make this provider agnostic? If so, I can help with abstraction, if not, I'll probably just do my own lib. Regardless, very nice integration!

Relies on legacy React context API

This package relies on the legacy React context API. Is there a plan to upgrade this?

If not, or for users who would like to take advantage of the new context API/React hooks, I've created a similar package, web3-react, which uses the latest API as well as React hooks (and was inspired by this package!).

Accessing the web3 object

Is there a way of accessing the web3 object directly? If I wanted to say send a transaction or look up a block how would I do this with this package?

Is there any way to customize the error message?

I would like to configure my own title and message when I initialize the Web3Provider component. Something like:

ReactDOM.render(
    <Web3Provider message={"You don't have MetaMask installed. Here is our instruction how to do that"}>
        <App />
    </Web3Provider>,
    document.getElementById('root')
);

Is there any way around to edit ErrorTemplate's props from my application?

Upgrade to React 16.2?

I'm using a higher version of React (16.2) but the peer dependency here isn't being met. Can this be upgraded to React 16.2 as well?

Throws error if no web3 at window

Working on using this with a project now but running into a snag if there is no web3 instance at all.
If I enable metamask everything works fine but when I disable the extension I'm getting this error instead of rendering Web3Unavailable.

screen shot 2019-03-02 at 3 55 13 pm

react-web3 not picking up user switching accounts

Hey, thanks for the great package.

I'm finding that the provider is not picking up on account changes initiated via metamask. It seems that the web3.eth.accounts is the culprit, which is not getting updated. However the async web3.eth.getAccounts(...) version does work.

I'm working on a react app bootstrapped with truffle. I'm not sure if it's an issue with my app set up or this package.

Cheers

how can i start project..

there is no scripts to start or run project....
"scripts": {
"test": "mocha-webpack --webpack-config webpack.config.js --require test/.setup.js test//*.test.js",
"test:watch": "mocha-webpack --watch --webpack-config webpack.config.js --require test/.setup.js test/
/*.test.js",
"build": "webpack --config webpack.config.js",
"build:watch": "webpack --config webpack.config.js --watch",
"prepare": "npm run build"

},

Custom component for no eth account available

Would be nice to have a way of passing your own component that shows up when no Eth account is available to tailor it to your app. And/or ability to style the default component. Might be easier just to be able to pass your own component through though

web3 1.0: MetaMask throws `TypeError: e is not a function` if web3 is imported

Hello, thanks a lot for this component, I like the idea a lot.

I'm trying to use it in a project that uses web3 1.0, but using react-web3 and also importing and instantiating web3 makes MetaMask throw a lot of TypeError: e is not a function errors. I'm not sure if this causes further problems, but is very annoying.

I can create a repo to reproduce the error if you need it.

By the way, where is the code for the 1.0.0 version of this library? None of the branches seem to have it.

Thanks!

Warning: Failed child context type: Invalid child context `web3.networkId` of type `string` supplied to `Web3Provider`, expected `number`. in Web3Provider (at src/index.js:13)

My App.js looks like this:

import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import { Web3Provider } from "react-web3";

ReactDOM.render(
  <Web3Provider>
    {/* <App /> */}
    <div>test</div>
  </Web3Provider>,
  document.getElementById("root")
);

serviceWorker.unregister();

The error disappears when I remove Web3Provider. I tried selecting different networks in MetMask but no change.

Screenshot 2019-08-02 at 12 23 22

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.