In this article we will cover Base64 in its entirety: we will learn what Base64 is and what it is used for. We will also learn about the characters of this method, the concepts of encoding and decoding. We’ll even show you the algorithm, not just in theory, but through examples: you’ll be able to encode and decode Base64 manually and in JavaScript.
, ,

Base64 in React Native: How to Encode & Decode

In this article you will learn about Base64 and React Native and how to use Base64 within React. Encoding and decoding is demonstrated through examples so that you can easily overcome the obstacles.

What is Base64?

Text-to-binary encoding schemes involve converting text characters into their binary representations. Each character is represented by a unique sequence of binary digits, typically based on ASCII or Unicode encoding standards.

Base64 is a specific binary-to-text encoding scheme that represents binary data using a set of 64 ASCII characters. It’s commonly used for encoding binary data, such as images or files, into text format for transmission over text-based protocols, like email or HTML. Base64 encoding groups three 8-bit bytes (24 bits) into four 6-bit characters, making it more space-efficient for encoding binary data in a text-friendly format.

What is React Native?

React Native is a free and open-source framework for creating mobile apps with JavaScript and React. Created by Facebook developers to build native mobile apps for iOS and Android from a single code base. React Native integrates React’s declarative UI components with native platform features, allowing developers to build high-performance mobile apps that look and feel like native programs. React Native takes an innovative method by leveraging JavaScript to manage native UI components, allowing developers to create mobile apps without having to master different programming languages.

When opposed to designing individual apps for each platform, this strategy provides for more efficient code reuse and shorter development cycles.

React Native has grown in popularity due to its potential to simplify mobile app development while providing a native-like user experience. Developers and businesses use it extensively to construct mobile apps for a wide range of reasons, including social media and e-commerce, as well as productivity and entertainment.

Does React Native Support Base64?

Through the JavaScript btoa() and atob() functions, React Native includes built-in support for Base64 encoding and decoding. Developers can use these functions to easily encode binary data to Base64 and decode Base64-encoded strings back to their original binary form.

The btoa() method accepts a string and returns a Base64-encoded version of that string. The atob() function, on the other hand, decodes a Base64-encoded string and returns the original binary data. These routines can be used to manage data translation between binary and text representations in React Native projects.

React Native’s Base64 support is very beneficial when working with APIs that require data to be communicated in Base64 format, or when dealing with binary data within the app, such as photos or files.

Base64 Encoding in React Native

Base64 encoding is a fundamental technique in data manipulation, allowing binary data to be represented in a text format. React Native makes it convenient to perform Base64 encoding using the built-in btoa() function, which stands for “binary to ASCII“. This function converts binary data into a Base64-encoded string.

To perform Base64 encoding in React Native, you can simply call the btoa() function and pass the binary data you want to encode as a parameter. The function will return the Base64-encoded representation of the data.

Example: Base64 Encoding in React

First, let’s look at a simple example where we ask for text in an input field, which is then converted to Base64 data by pressing a button.

import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';

const Base64Encoder = () => {
  // State variables to store the input text and encoded text
  const [text, setText] = useState('');
  const [encodedText, setEncodedText] = useState('');

  // Function to encode the input text to Base64
  const encodeToBase64 = () => {
    // Using the btoa function to encode the text
    const encoded = btoa(text);
    setEncodedText(encoded);
  };

  return (
    <View style={{ padding: 20 }}>
      {/* TextInput for entering the text */}
      <TextInput
        placeholder="Enter text"
        style={{ borderBottomWidth: 1, marginBottom: 10, padding: 5 }}
        value={text}
        onChangeText={setText}
      />
      {/* Button to trigger the encoding */}
      <Button title="Encode to Base64" onPress={encodeToBase64} />
      {/* Display the encoded text */}
      {encodedText ? (
        <View style={{ marginTop: 20 }}>
          <Text>Encoded Text:</Text>
          <Text>{encodedText}</Text>
        </View>
      ) : null}
    </View>
  );
};

export default Base64Encoder;

This code defines a React Native component named Base64Encoder. It utilizes the useState hook to manage two state variables: text to store the input text and encodedText to store the Base64-encoded result.

The encodeToBase64 function is responsible for encoding the input text using the btoa function, which is a built-in JavaScript function for Base64 encoding. The encoded result is stored in the encodedText state.

The component renders a View containing a TextInput for entering the text, a Button for triggering the encoding process, and a Text element to display the encoded result if available.

Example: Convert PDF to Base64 in React

Here is an illustration and explanation of how to convert a PDF file to Base64 using React:

import React, { useState } from 'react';

const PdfToBase64Converter = () => {
  const [base64Data, setBase64Data] = useState('');

  const handleFileInputChange = async (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64String = e.target.result.split(',')[1];
        setBase64Data(base64String);
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div>
      <input type="file" accept=".pdf" onChange={handleFileInputChange} />
      {base64Data && (
        <div>
          <h3>Base64-encoded PDF content:</h3>
          <textarea
            style={{ width: '100%', height: '200px' }}
            value={base64Data}
            readOnly
          />
        </div>
      )}
    </div>
  );
};

export default PdfToBase64Converter;

This React component, PdfToBase64Converter allows the user to select a PDF file using an input element of type “file.” When a file is selected, the handleFileInputChange function is triggered.

Inside the handleFileInputChange function, an FileReader instance is created. The onload event handler of the reader is used to read the contents of the selected PDF file. The contents are read as a data URL, which includes the Base64-encoded data of the file. The actual Base64-encoded content is extracted from the data URL and stored in the base64Data state using the setBase64Data function.

The component’s return includes the input element for selecting the PDF file. If base64Data is not empty, it displays the Base64-encoded content in a textarea.

Base64 Decoding in React

The process of turning a Base64-encoded string back into its original binary representation is known as decoding. React Native makes Base64 decoding easier by including the atob() function, which stands for “ASCII to binary“. This method accepts a Base64-encoded string and returns the underlying binary data.

To do Base64 decoding in React Native, use the atob() function and send the Base64-encoded string as an argument. The actual binary data will then be returned by the function.

Example: Base64 Decoding in React Native

Here is an illustration of how to decode a Base64-encoded string in React Native and restore its original content:

import React, { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

const Base64Decoder = () => {
  const [encodedData, setEncodedData] = useState('');
  const [decodedData, setDecodedData] = useState('');

  const handleDecodePress = () => {
    try {
      const decodedString = atob(encodedData); // Use the atob function for decoding
      setDecodedData(decodedString);
    } catch (error) {
      console.error('Error decoding Base64:', error);
    }
  };

  return (
    <View>
      <TextInput
        style={{ borderBottomWidth: 1, marginBottom: 10 }}
        placeholder="Enter Base64-encoded string"
        value={encodedData}
        onChangeText={setEncodedData}
      />
      <Button title="Decode" onPress={handleDecodePress} />
      {decodedData !== '' && (
        <View>
          <Text>Decoded content:</Text>
          <Text>{decodedData}</Text>
        </View>
      )}
    </View>
  );
};

export default Base64Decoder;

At its core, the Base64Decoder component uses the useState hook from the React library to manage its internal state. This hook allows the component to define two pieces of state: encodedData and decodedData, both of which are initialized to an empty string. The setEncodedData and setDecodedData functions are used to update these pieces of state.

The component also defines a function named handleDecodePress, which is called when the user presses the “Decode” button. This function uses the global atob function to decode the encodedData string and stores the result in the decodedData piece of state. If an error occurs during decoding, it is logged to the console.

The user interface of the Base64Decoder component is simple and intuitive. It consists of a View element containing a TextInput element, a Button element, and a conditional View element. The TextInput element allows the user to enter a Base64-encoded string, which is stored in the encodedData piece of state. The Button element has a title of “Decode” and calls the handleDecodePress function when pressed. The conditional View element is only rendered if the decodedData string is not empty, and it displays the decoded content.

Example: Convert Base64 to PDF in React Native

Here is an example of a straightforward React Native app that decodes a Base64-encoded PDF string and produces a corresponding PDF file.

import React, { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

const Base64ToPdfExample = () => {
  const [base64Data, setBase64Data] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  const handleConvertPress = () => {
    try {
      const pdfBlob = RNFetchBlob.base64ToBlob(base64Data, 'application/pdf');
      const outputPath = `${RNFetchBlob.fs.dirs.DownloadDir}/converted.pdf`;

      RNFetchBlob.fs
        .writeFile(outputPath, pdfBlob, 'base64')
        .then(() => setErrorMessage('PDF converted successfully!'))
        .catch(error => setErrorMessage(`Conversion error: ${error.message}`));
    } catch (error) {
      setErrorMessage(`Invalid Base64 input: ${error.message}`);
    }
  };

  return (
    <View>
      <TextInput
        multiline
        placeholder="Enter Base64-encoded PDF"
        value={base64Data}
        onChangeText={text => setBase64Data(text)}
      />
      <Button title="Convert to PDF" onPress={handleConvertPress} />
      <Text>{errorMessage}</Text>
    </View>
  );
};

export default Base64ToPdfExample;

Explanation:

  1. Importing Dependencies and Setting up State:
    • Similar to the previous examples, this code imports necessary components from react-native and rn-fetch-blob packages.
    • It uses the useState hook to manage state: base64Data holds the input Base64 data, and errorMessage is used to display conversion-related messages.
  2. Defining the handleConvertPress Function:
    • This function is triggered when the “Convert to PDF” button is pressed.
    • It uses the base64ToBlob method from RNFetchBlob to convert the Base64 data into a Blob object of MIME type ‘application/pdf’.
    • The converted PDF Blob is then written to a file using writeFile, specifying the output path and the base64 encoding.
    • If the conversion is successful, a success message is displayed; otherwise, an error message is shown.
  3. UI Rendering in the return Statement:
    • The UI consists of a TextInput where users can input the Base64-encoded PDF.
    • The “Convert to PDF” button initiates the conversion process when pressed.
    • The errorMessage state is displayed to inform the user about the conversion outcome.

React File Base64 Functional Component

The react-file-base64 is an npm package that provides a React component for Base64 encoding of files. You can use this component by installing npm i with react-file-base64, then importing and using it in your project.

Managing files and how they interact with other files within components is a typical necessity in React. A functional component that enables users to choose a file from their local system and convert it to a Base64-encoded string is the main goal of the “React File Base64 Functional Component” project. When a file’s content needs to be communicated as text data, such as when uploading photographs or files to a server, this method is especially helpful.

To offer a seamless user experience, the functional component makes use of React’s state management and event handling techniques. Developers can simplify processing file uploads and seamlessly include them into their programs by letting users select files and converting them to Base64. This chapter will walk developers through the process of creating the “React File Base64 Functional Component,” which will enable them to manage files within their React projects effectively.

Here is a simple example of how to use the react-file-base64 package to convert a file to Base64 in a React application:

import React, { useState } from 'react';
import FileBase64 from 'react-file-base64';

const MyComponent = () => {
  const [file, setFile] = useState(null);

  const handleFileUpload = (file) => {
    setFile(file);
    console.log(file);
  };

  return (
    <div>
      <FileBase64 onDone={handleFileUpload} />
      {file && <p>File name: {file.name}</p>}
      {file && <p>File size: {file.size}</p>}
      {file && <p>File type: {file.type}</p>}
    </div>
  );
};

export default MyComponent;

This code creates a FileBase64 component that allows the user to select a file. When the user selects a file, the handleFileUpload function is called with the selected file as an argument. This function sets the file state variable and logs the file object to the console.

The file object contains information about the selected file, such as its name, size, and type. It also contains a base64 property that holds the Base64 encoded content of the file.

React Document Picker and Base64

The react-native-document-picker package is used in React Native applications to select documents from the user’s device. This package allows the user to select the desired document and returns its URI. You can use the received URI to access and display the file’s contents in your application.

If you want to convert the selected document into Base64 format, you could use a package like rn-fetch-blob. This package will read the file from the given URI and convert it to Base64 format.

Here is an example:

import React from 'react';
import { Button, Text, View } from 'react-native';
import DocumentPicker from 'react-native-document-picker';

const MyComponent = () => {
  const handlePress = async () => {
    try {
      const result = await DocumentPicker.pick({
        type: [DocumentPicker.types.allFiles],
      });
      console.log(
        `URI: ${result.uri}\nType: ${result.type}\nName: ${result.name}\nSize: ${result.size}`
      );
    } catch (err) {
      if (DocumentPicker.isCancel(err)) {
        // User cancelled the picker
      } else {
        throw err;
      }
    }
  };

  return (
    <View>
      <Button title="Pick Document" onPress={handlePress} />
    </View>
  );
};

export default MyComponent;

React Doc Viewer and Base64

The react-doc-viewer is an npm package that provides a document viewer component for React applications. This component is capable of displaying various types of files, including PDFs, images, and Microsoft Office documents. It can be used to easily embed and display documents within a React application.

To use react-doc-viewer, you can install it using the command npm install react-doc-viewer and then import it into your project. The package provides a DocViewer component that accepts an array of file objects as a prop. Each file object should contain the file URL and the file type.

Here is an example of how to use the DocViewer component to display a PDF file:

import React from 'react';
import { DocViewer } from 'react-doc-viewer';

const MyComponent = () => {
  const files = [
    {
      uri: 'https://example.com/myfile.pdf',
      fileType: 'pdf'
    }
  ];

  return <DocViewer files={files} />;
};

export default MyComponent;