How to use web3.eth in Reactjs

In Javascript

let web3
web3 = await Moralis.Web3.enable()
const contract = await new web3.eth.Contract(contractABI, CONTRACT_ADDRESS)

How to write code like that in reactjs

1 Like

theres so may ways you can do it. I personally would use the web3React library as it has greadt wallet support. howeveer if you want to keep things simple like straight out of the box you could just declare web3 like you usually would in app.js and then pass web3 as props to the componennts you need or else you make a hook and enable web3 in the hoook then use the web3Hook in whatever components you need for things like contract interactions

Can I do it ?
const { 
	web3, enableWeb3
} = useMoralis();

useEffect(() => {
          const checkWeb3 = async () => {
               if(!isWeb3Enabled) {
                    enableWeb3()
               }
          }
          checkWeb3()
}, [])

web3.eth.Contract(ContractABI, ContractAddress)
1 Like

no i dont think that will because if you refresh the page web3 will come up as undefined because the useEffcect hasnt defined the web3 object yet. thats why its best to segregate all of this logic into its own hook and use it high up in your cmpoent tree and passs web3 down as props. However, althought its not the best way you could just init the contract in your useEffect but are you planning on supporting multiple wallets. If so you should look into web3React or i think moralis provider their own wallet support components that you can use because your provider is going to be different depending on what wallet you use and will make your code a lot more complicated to be able to switch providers etc. But in the most simple implementation with just metaask initing your contract in the useEffect would be fine although not the most elegant way to do it