Categories
JavaScript React

How to add an Input Mask in a React App – an Example

Introduction

An input mask is a string expression that constrains user input.

In this article, we’ll look at how to use an input mask to enforce input format in a React app.

Getting Started

We can add an input that enforces an input mask in a React app.

The react-input-mask package makes this very easy.

First, we run:

npm install react-input-mask --save

to install the package in our React project.

Then we can use it by adding it component provided by the package and specify the format of the input that we want to accept.

For instance, if we want to incorporate an input that takes a North American phone number, then we can write:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  return (
    <div className="App">
      <InputMask mask="+1\(999) 999-9999" maskChar=" " />
    </div>
  );
}

The mask prop has the input mask.

And the maskChar has the character we want to cover over the unfilled parts of a mask.

We can also use the formatChars prop to specify the format characters with the characters as keys and the corresponding regex string as a value.

alwaysShowMask is a boolean prop to specify whether we want to show the mask when input is empty and has no focys.

inputRef prop lets us specify the input ref of the input element so that we can manage focus, selection, etc.

We can use the formatChars prop as follows:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  return (
    <div className="App">
      <InputMask
        formatChars={{
          "9": "[0-9]",
          a: "[A-Za-z]",
          "*": "[A-Za-z0-9]"
        }}
        mask="+1\(999) 999-9999"
        maskChar=" "
      />
    </div>
  );
}

Setting State

We can set the input value to a state by using a change handler and the useState hook as usual with the InputMask component.

For instance, we can write:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  const [phone, setPhone] = React.useState("");
  return (
    <div className="App">
      <InputMask
        value={phone}
        onChange={e => setPhone(e.target.value)}
        mask="+1\(999) 999-9999"
        maskChar=" "
      />
      <p>{phone}</p>
    </div>
  );
}

We added onChange={e => setPhone(e.target.value)} to call setPhone when the input value changes.

It also takes a value prop so that we can set the input value to the phone number that we can change.

Now when we type something into the input, we’ll see the inputted value displayed below it.

Conclusion

We can add input with format being enforced by an input mask by using the react-input-mask package.

Using the component in the package, we can set the mask to enforce the format and handle input value changes like a regular input element.

The mask format can also be adjusted to our liking.

Categories
HTML JavaScript

Javascript – Create an Element with Attributes

We can create an HTML element with JavaScript that has various attributes by calling a few methods and setting a few properties.

First, we call the document.createElement method with the tag name of the element that we want to create as a string.

Then we set the attributes of our newly created element by setting the properties of the newly created object.

Finally, we attach the element to the element that we want our element to be in as a child element by calling the appendChild method of the element that want our element to stay inside of with our newly created element as the argument.

For instance, if we create a new input element, we write:

const input = document.createElement('input');

to create an element with the input tag.

Then we can set the type, id, name, value, and readonly attributes of our newly created input element by writing:

input.id = 'foo-input';
input.name = 'foo';
input.value = 'bar';
input.readOnly = true;

We set the id property to set the id attribute of our input element.

The name property sets the name property of our element.

value sets the value attribute of our element.

And readOnly sets the readonly attribute of our element. The case is different with this attribute. In HTML, it’s readonly and in JavaScript it’s readOnly.

Once we did that, we can call appendChild on the parent element that we want our input element to be in with the input element as the argument.

For instance, if we want the input element we created to be in the body element, we can write:

document.body.appendChild(input);

Once we did that, we should see something like:

<input id="foo-input" name="foo" readonly="">

when we inspect the element. And ‘bar’ will be displayed on the screen inside the input box.

We can create an element with attributes with JavaScript by first calling createElement, then we can set the properties which correspond to the HTML attribute that we want to set.

Then to display it, we call appendChild on the parent element that we want our element to be displayed in with our newly created object as the argument.

Categories
HTML JavaScript

Javascript – How to Add a Style to an Element

We can add a style to an element by using the style property of an object.

To style an element, first we have to get the element that we want to style.

We can do this easily with document.querySelector, which takes a string with any CSS selector.

For instance, if we have the following div:

<div class='foo'>
  foo
</div>

We can get div by the class. We can write:

const el = document.querySelector('.foo');

to get the div element with the class foo that we have above.

Then we can set the styles according to the properties list below at MDN.

The CSS and the JavaScript equivalents are listed on that page.

For instance, if we want to set the color of the content inside the div we have above, we can set the color property as follows:

el.style.color = 'green';

The code above sets the color property of the style property to 'green'.

This will turn the text in the div green.

We can do the same thing with any property name in the ‘JavaScript’ column at this page.

We can set the style of an element is simple with JavaScript. However, we shouldn’t do that too frequently so that our browsers won’t be too busy setting styles for elements with JavaScript.

Categories
JavaScript JavaScript Basics

How to Add an ID to Element with Javascript

We can add an ID to a given element with JavaScript.

To do this, first we get the element. We can use the following methods:

  • document.querySelector
  • document.querySelectorAll
  • document.getElementById
  • document.getElementsByTagName

We probably want to use anything other than getElementById since our element doesn’t have an ID yet.

document.querySelector can get an element with any CSS selector and return it.

For instance, given that we have an element with class foo, we can write:

const el = document.querySelector('.foo');

With querySelectorAll, it returns a NodeList with all elements with the given CSS selector.

So we’ve to find the one that’s right for us. But assuming that we want the first element, we can write:

const el = document.querySelectorAll('.foo')[0]

With getElementsByTagName, we can get all the elements by their tag name.

For instance, we can write:

const el = document.getElementsByTagName('div')[0]

to get all the divs with the given name.

In all cases, we can get an HTMLElement object, which has the id property, which we can use to set the ID of an element by assigning a string to it.

We can write:

el.id = 'bar';

to set the ID of el above to bar.

The id property of an HTMLElement can be set to let us add an ID to the element of our choice with JavaScript.

Categories
HTML JavaScript jQuery

How to Find an Element by Name with jQuery

We can find an element with the given name with jQuery by using the $ itself.

For instance, if we want to find something with the name foo, we can write:

$('[name=foo]')

The general form of this CSS selector is:

[attribute=value]

In the example above name is the attribute and foo is the value of the name attribute.

Then that will return the element with the name foo.

Once we did that, if the element exists on the page, then we can do anything with it like adding/removing classes, adding/removing styles, and so on.