React Base64 Decode

In this tutorial, you will learn how to decode and encode strings in base64 using two JavaScript functions: atob and btoa. We will give two examples: in the first example, you will see how to encode a string into base64, and in the second example, you will see how to decode a base64 string back to its original form.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
React Js Encode String into Base64 Example
Copied to Clipboard
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [inputString, setInputString] = useState("fontawesomeicons.com");
const [encodedString, setEncodedString] = useState("Zm9udGF3ZXNvbWVpY29ucy5jb20=");
const handleInputChange = (event) => {
setInputString(event.target.value);
}
const handleEncodeClick = () => {
const encoded = btoa(inputString);
setEncodedString(encoded);
}
return (
<div className="container">
<label htmlFor="input">Input string:</label>
<input type="text" id="input" value={inputString} onChange={handleInputChange} />
<button onClick={handleEncodeClick}>Encode to Base64</button>
<label htmlFor="output">Encoded string:</label>
<textarea id="output" value={encodedString} readOnly />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of React Js Encode to base64
Example 2 : How to Decode Base64 in React Js?
In the previous example, we saw how to encode a string into base64 using the btoa function. In this example, we will explain how to decode a base64 string back to its original form using the atob function. This can be useful for retrieving the original data that was encoded in base64.
Base64 Decode React
Copied to Clipboard
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [inputString, setInputString] = useState("Zm9udGF3ZXNvbWVpY29ucy5jb20=");
const [decodedString, setdecodedString] = useState("");
const handleInputChange = (event) => {
setInputString(event.target.value);
}
const handleDecodeClick = () => {
const decoded = atob(inputString);
setdecodedString(decoded);
}
return (
<div className="container">
<h3>React Js atab() function </h3>
<p>Decode base64 sting in React Js</p>
<label htmlFor="input">Input string:</label>
<input type="text" id="input" value={inputString} onChange={handleInputChange} />
<button onClick={handleDecodeClick}>Decode Base64</button>
<label htmlFor="output">Decoded string:</label>
<textarea id="output" value={decodedString} readOnly />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of Base64 Decode in ReactJs
Ad