Connect MetaMaskWallet to Frontend on Binance Smart Chain (Part 3)

Phyzixmusic
Hexmount
Published in
2 min readApr 4, 2021

You’ve made it to the final part of this guide! This is where the real fun begins.

In the last parts of this guide series, we covered some basic smart contracts and wrote some logic for Metamask that we will use as part of our React web app. If you didn't check out the last part of this guide, you can do so here:

Now we need to import the create ethereum.js script into the React app.

Note: You do not have to use React to integrate with a smart contract on Binance but it's the most standard solution.

Our simple app looks like this

we will import ethereum.js into our main App.js component,

import React, { useState, useEffect } from 'react';
import getBlockchain from './ethereum.js';

function App() {
const [simpleStorage, setSimpleStorage] = useState(undefined);
const [data, setData] = useState(undefined);

useEffect(() => {
const init = async () => {
const { simpleStorage } = await getBlockchain()
// load contract data
const data = await simpleStorage.readData();
setSimpleStorage(simpleStorage);
setData(data);
};
init();
}, []);

const updateData = async e => {
e.preventDefault();
const data = e.target.elements[0].value;
const tx = await simpleStorage.updateData(data);
await tx.wait();
const newData = await simpleStorage.readData();
setData(newData);
};
// only load if contract is successfully loaded
if(
typeof simpleStorage === 'undefined'
|| typeof data === 'undefined'
) {
return 'Loading...';
}

return (
<div className='container'>
<div className='row'>

<div className='col-sm-6'>
<h2>Data:</h2>
<p>{data.toString()}</p> // render data variable
</div>

<div className='col-sm-6'>
<h2>Change data</h2>
<form className="form-inline" onSubmit={e => updateData(e)}>
<input
type="text"
className="form-control"
placeholder="data"
/>
<button
type="submit"
className="btn btn-primary"
>
Submit
</button>
</form>
</div>

</div>
</div>
);
}

export default App;

If we pass some new value to the smart contract by triggering updateData function asynchronously, MetaMask will then take over and show a pop-up to confirm the transaction.

Once the transaction is confirmed, we must trigger the trx.wait() function to wait until the transaction is mined. As soon as a change of data in the app’s internal state is detected, React will re-render the component in render() function to show the new value data variable.

Congrats! You’ve connected Metamask to your new React web app!

If you’ve enjoyed this guide, please drop a comment or give us a clap :)

--

--