Mask Email Addresses with Custom React Component for Display Purposes

Kanan Rahimov
2 min readApr 30, 2023
Email mask React component in action

Overview

In this tutorial, we will demonstrate how to create a custom React component that masks email addresses for display purposes. This component will hide part of the email’s username and domain to protect user privacy. We will start by building the component in JavaScript (JSX), then rewrite it in TypeScript (TSX) for improved type safety and error-checking. By the end of this tutorial, you will have a reusable EmailMask component that you can easily integrate into your React applications.

Prerequisites

  • Basic knowledge of React and JavaScript/TypeScript
  • A React project is set up and ready to go

Create the EmailMask Component in JavaScript (JSX)

  1. Create a new file called EmailMask.js in your components directory.
  2. Paste the following code into the EmailMask.js file:
import React from 'react';

const VISIBLE_USERNAME_LENGTH = 3;
const VISIBLE_DOMAIN_LENGTH = 2;

const EmailMask = ({ email, maskCharacter = '*', maskDomain = false }) => {
const [username, domain] = email.split('@');
const [domainName, topLevelDomain] = domain.split('.');

const visibleUsernameLength =…

--

--