reactjsweb3-react

How can I prevent metamask from popping up?


I followed a tutorial on youtube on how to create a button to connect metamask with my Dapp, I got a problem is when I've launched the Dapp metamask pop up even before I click on the button to connect to it, I've tried to remove the web3.js code from the app.js because I know is that "web3 = new Web3(window.ethereum);" who makes metamask to popup but I got another problem in my App.js.

Index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Web3ReactProvider } from '@web3-react/core';
import Web3 from "web3";

// get and inject web3 provider
const getLibrary = (provider) => {
    return new Web3(provider)
};


ReactDOM.render(
  <React.StrictMode>
    <Web3ReactProvider getLibrary={getLibrary}>
    <App />
    </Web3ReactProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js code

 import web3 from './web3';
    import { useWeb3React } from "@web3-react/core";
    import { injected } from "./components/Wallet/connector";
    
    
    const { active, account, library, connector, activate, deactivate } = useWeb3React();
    
    
      // Connect to metamask
      const Connect = async () => {
        try {
         await activate(injected);
         
        } catch(err) {
          console.log(err)
        }
      }

const winnerHandler = async () => {
    // get the accounts
    const account = await web3.eth.getAccounts();

  
    // Call the pickWinner function from the contract
    await lottery.methods.pickWinner().send({
      from: account[0]
    });

 
  }
    
    <main>
        <Navbar>
            <Left>
              <Logo>LTR</Logo>
            </Left>
              <Right>
              {active ? <Button widthBtn hightBtn >{account.substring(0,13)}...</Button> :
               <Button widthBtn hightBtn  onClick={Connect}>Connect MetaMask</Button>} 
              </Right>
          </Navbar>
    </main>

web3.js code

import Web3 from "web3";

let web3;

if (window.ethereum && window.ethereum.isMetaMask) {
    console.log('MetaMask Here!');
    web3 = new Web3(window.ethereum);

    window.ethereum.request({ method: 'eth_requestAccounts'})
    
} else {
    console.log('Need to install MetaMask');
    window.Error('Please install MetaMask browser extension to interact');
}

export default web3;

Solution

  • I just met this problem today. You need to change the function in the onClick on the app.js

    From:

     <Button widthBtn hightBtn  onClick={Connect}>Connect MetaMask</Button>}
    

    To:

    <Button widthBtn hightBtn  onClick={()=>Connect}>Connect MetaMask</Button>}