Welcome folks today in this blog post we will be converting image to base64
code and display it inside textarea
widget in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js project using the below command as shown below
npx create-react-app sampleapp
And after that you need to copy paste the code inside the App.js
file as shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import React from "react"; import "./styles.css"; export default function App() { const onChange = e => { const files = e.target.files; const file = files[0]; getBase64(file); }; const onLoad = fileString => { console.log(fileString); this.base64code = fileString }; const getBase64 = file => { let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { onLoad(reader.result); }; }; return ( <div className="App"> <form> <input type="file" onChange={onChange} /> <textarea rows="50" cols="50" value={this.base64code}></textarea> </form> </div> ); } |
As you can see we are showing the input
field where we can allow the user to upload an image
file and then we have the textarea
widget where we show the base64
code of the image. And after that we have binded the onchange
event handler in which we have defined the javascript code. Here inside the function we are using the fileReader
to read the image and then we are showing the base64
code of the image and then showing the code
inside the textarea.