Hide a button

Good evening, I have a button that I would like to not display when we are not connected, otherwise it is displayed?

I did this piece of code I guess I must have the variable like this

Can you help me ?

const [connected, setConnected] = useState(true);
setConnected(false);

<button className="connectBTN" onClick={init} disabled={!connected}> {connected ? "Connect Metamask" : "Connected"}</button>
    </div>

Hi @cdevl3749 , how is this supposed to work? You’re initialising connected as true, then immediately setting it to false (effective with the next render) and that was it.

Where and when would you actually determine whether you’re “connected” or not?

Good morning,

In fact, I spelled it wrong, sorry.

I have my page where you have to connect with Metamask if you want to see the data and it works very well and I would like to do the same with the “FAQ” button so that you can see it only if you are connected to Metamask

The code of my button where I would like to make the condition

return (
    <section className="contact-section">
        <h1 className="title">
           Consulter la FAQ !
        </h1>

         <a href="http://localhost:5173/faq/index.html" target='_blank' rel="noopener noreferrer">
        <button className="downlodeBTN">
              FAQ
        </button>
        </a>
 </section>
    )

The code where I connect with Metamask

import { useState } from "react";
import ABI from "./ABI.json";
import Web3 from "web3";
import './Wallet.css';

const Wallet = ({ saveState }) => {
  const [connected, setConnected] = useState(true);
  const isAndroid = /android/i.test(navigator.userAgent);
  const init = async () => {
    try {
      const web3 = new Web3(window.ethereum);
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      const contract = new web3.eth.Contract(
        ABI,
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      );
      setConnected(false);
      saveState({ web3: web3, contract: contract });
    } catch (error) {
      alert("Please Install Metamask");
    }

  }
  return <>
    <div className="header">
      {isAndroid && <button className="connectBTN">
        <a href="https://metamask.app.link/dapp/sriche.netlify.app/">Click For Mobile</a>
      </button>}
      <button className="connectBTN" onClick={init} disabled={!connected}> {connected ? "Connect Metamask" : "Connected"}</button>
    </div>
  </>
}
export default Wallet;

To conditionally show the FAQ button based on MetaMask connection, use this React code:


import React, { useState, useEffect } from 'react';

const ContactSection = () => {
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const checkMetaMask = async () => {
      if (window.ethereum) {
        const accounts = await window.ethereum.request({ method: 'eth_accounts' });
        setIsConnected(accounts.length > 0);
      }
    };
    checkMetaMask();
  }, []);

  return (
    <section className="contact-section">
      <h1 className="title">Consulter la FAQ !</h1>
      {isConnected && (
        <a href="http://localhost:5173/faq/index.html" target='_blank' rel="noopener noreferrer">
          <button className="downlodeBTN">FAQ</button>
        </a>
      )}
    </section>
  );
};

export default ContactSection;
1 Like

Thanks for the clarification. So that’s a different FAQ Button Component located somewhere else where you want to do this check? In this case, you might try passing the state (as set with saveState) to that component, and check if it’s actually set.

If this is not feasible directly, you might have a look at the useContext() hook:

1 Like

Good morning,

Thank you for your help I tested your code and the button does not appear.

The snippet posted by @averyjonesss888 diverges from yours in a couple of aspects, but the crucial bit might be that they’re setting the connected state depending on the ethereum response:

setIsConnected(accounts.length > 0);

So for the purpose of testing, try to just

setIsConnected(true);

Also carefully review their snippet. They have the connected state the other way round (justifiably IYAM), and they’re using a dedicated effect for the contact section. If you’re using this check a lot, this would mean a new request for each such component, where you might actually just check the state you already saved inside the Wallet component.

PS: AFAICT you might actually drop the useState() hook altogether, and infer connected state from the state you stored somewhere above with saveState().

1 Like

PPS: Well okay, maybe you still need useState() to disable the button while the request is in flight. Here’s a very minimal, self contained example:

1 Like

with this line it works, the problem is that the button should only be there if I am connected to Metamask

setIsConnected(true);

Yes that line (and only that line BTW) was supposed to be replaced for the purpose of testing only. If this works, you can go ahead and implement an actual connection check… that’s what accounts.length > 0 is supposed to do I guess.

I’m not familiar with the ethereum API myself though. @averyjonesss888 maybe you can elaborate?

Good morning,

I have a page where when I connect to Metamask it displays the data from my smart contract and I would simply like to ensure that when I connect it displays the “FAQ” button otherwise not.

here is the code:

Wallet.jsx

import { useState } from "react";
import ABI from "./ABI.json";
import Web3 from "web3";
import './Wallet.css';

const Wallet = ({ saveState }) => {
  const [connected, setConnected] = useState(true);
  const isAndroid = /android/i.test(navigator.userAgent);
  const init = async () => {
    try {
      const web3 = new Web3(window.ethereum);
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      const contract = new web3.eth.Contract(
        ABI,
        "0x4563599531D24065a5041D1a8c599CAD7c855648"
      );
      setConnected(false);
      saveState({ web3: web3, contract: contract });
    } catch (error) {
      alert("Please Install Metamask");
    }

  }
  return <>
    <div className="header">
      {isAndroid && <button className="connectBTN">
        <a href="https://metamask.app.link/dapp/cdevl.netlify.app/">Click For Mobile</a>
      </button>}
      <button className="connectBTN" onClick={init} disabled={!connected}> {connected ? "Connect Metamask" : "Connected"}</button>
    </div>
  </>
}
export default Wallet;

et mon bouton ou je voudrais faire les modifications

import { useState, useEffect } from "react";
import './Contact.css'

const Contact = ({ state }) => {
    const [resume, setResume] = useState("");
    useEffect(() => {
        const { contract } = state;
        const resumeDetails = async () => {
            const resumeCid = await contract.methods.resumeLink().call();
            setResume("https://gateway.pinata.cloud/ipfs/" + resumeCid);
        }
        contract && resumeDetails();
    }, [state])

    return (
        <section className="contact-section">
            <h1 className="title">
                Consulter la FAQ !
            </h1>

            <a href="../faq/index.html" target='_blank' rel="noopener noreferrer">
                <button className="downlodeBTN">
                    FAQ
                </button>
            </a>
        </section>
    )
}

export default Contact

How do you determine whether you’re connected or not? Is there some property in your state object that would qualify?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.