Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Get the Short Name of a Month in JavaScript

To get the short name of a month in JavaScript, create a Date object with the given month, then call the toLocaleString() method on the Date with a given locale and a set of options. One of the options should specify that the month name should be in a short form.

For example, here’s how we can get the 3-letter month name:

function getMonthShortName(monthNo) {
  const date = new Date();
  date.setMonth(monthNo - 1);

  return date.toLocaleString('en-US', { month: 'short' });
}

console.log(getMonthShortName(1)); // Jan
console.log(getMonthShortName(2)); // Feb
console.log(getMonthShortName(3)); // Mar

We can get the 1-letter month name by setting month to narrow:

function getMonthShortName(monthNo) {
  const date = new Date();
  date.setMonth(monthNo - 1);

  return date.toLocaleString('en-US', { month: 'narrow' });
}

console.log(getMonthShortName(1)); // J
console.log(getMonthShortName(2)); // F
console.log(getMonthShortName(3)); // M

Our getMonthShortName() function takes a position and returns the short name of the month with that position.

The setMonth() method sets the month of a Date object to a specified number.

Note

The value passed to setMonth() is expected to be zero-based. For example, a value of 0 represents January, 1 represents February, 2 represents March, and so on. This why we pass the value of 1 subtracted from the month number (monthNumber - 1) to setMonth().

Date toLocaleString() method

We used the Date toLocaleString() method to get the name of the month of the date. toLocaleString() returns a string with a language-sensitive representation of a date.

This method has two parameters:

  1. locales: A string with a BCP 47 language tag, or an array of such strings. There are many locales we can specify, like en-US for US English, en-GB for UK English, and en-CA for Canadian English.
  2. options: An object used to adjust the output format of the date.

In our examples, we pass en-US as the language tag to use US English, and we set values of short and narrow to the month property of the options object to display the short name of the month.

We can pass an empty array ([]) as the first argument to make toLocaleString() use the browser’s default locale:

function getMonthShortName(monthNo) {
  const date = new Date();
  date.setMonth(monthNo - 1);

  // Use the browser's default locale
  return date.toLocaleString([], { month: 'short' });
}

console.log(getMonthShortName(1)); // Jan
console.log(getMonthShortName(2)); // Feb
console.log(getMonthShortName(3)); // Mar

This is good for internationalization, as the output will vary depending on the user’s preferred language.

Intl.DateTimeFormat object

Using the toLocaleString() means that you have to specify a locale and options each time you want a language-sensitive short name of the month. To use the same settings to format multiple dates, we can use an object of the Intl.DateTimeFormat class instead.

For example:

function getTwoConsecutiveMonthNames(monthNumber) {
  const date1 = new Date();
  date1.setMonth(monthNumber - 1);

  const date2 = new Date();
  date2.setMonth(monthNumber);

  const formatter = new Intl.DateTimeFormat('en-US', { month: 'short' });

  // Format both dates with the same locale and options
  const firstMonth = formatter.format(date1);
  const secondMonth = formatter.format(date2);

  return `${firstMonth} & ${secondMonth}`;
}

console.log(getTwoConsecutiveMonthNames(1)); // Jan & Feb
console.log(getTwoConsecutiveMonthNames(2)); // Feb & Mar
console.log(getTwoConsecutiveMonthNames(3)); // Mar & Apr

How to Convert JSON to XML in JavaScript

We can use the xml-js library to easily convert a JSON string to an XML string in JavaScript.

import { json2xml } from 'xml-js';

const jsonObj = {
  name: 'Garage',
  cars: [
    { color: 'red', maxSpeed: 120, age: 2 },
    { color: 'blue', maxSpeed: 100, age: 3 },
    { color: 'green', maxSpeed: 130, age: 2 },
  ],
};

const json = JSON.stringify(jsonObj);

const xml = json2xml(json, { compact: true, spaces: 4 });

console.log(xml);

This code will have the following output:

<name>Garage</name>
<cars>
    <color>red</color>
    <maxSpeed>120</maxSpeed>
    <age>2</age>
</cars>
<cars>
    <color>blue</color>
    <maxSpeed>100</maxSpeed>
    <age>3</age>
</cars>
<cars>
    <color>green</color>
    <maxSpeed>130</maxSpeed>
    <age>2</age>
</cars>

Install xml-js

Before using xml-js, we’ll need to install it in our project. We can do this with the NPM CLI.

npm i xml-js

Or with the Yarn CLI:

yarn add xml-js

After installation, we’ll be able to import it into a JavaScript module, like this:

import { json2xml } from 'xml-js';

We use import destructuring to access the json2xml() method directly from the library.

For a CommonJS module, we’ll import it like this instead:

const { json2xml } = require('xml-js');

The json2xml() function

The json2xml() function from the library has two parameters. The first is the JSON string to convert to XML, and the second is an object.

const xml = json2xml(json, { compact: true, spaces: 4 });

Customize conversion of JSON to XML

This object is used to specify various options for customizing the conversion process.

In our example, we set the compact property to true to indicate that the JSON string input is in a compact form.

We set the spaces property to 4 to indent nested XML nodes by 4 spaces. So we can reduce the indentation by setting spaces to 1:

import { json2xml } from 'xml-js';

const jsonObj = {
  name: 'Garage',
  cars: [
    { color: 'red', maxSpeed: 120, age: 2 },
    { color: 'blue', maxSpeed: 100, age: 3 },
    { color: 'green', maxSpeed: 130, age: 2 },
  ],
};

const json = JSON.stringify(jsonObj);

const xml = json2xml(json, { compact: true, spaces: 1 });

console.log(xml);

Now we will have the following XML output:

<name>Garage</name>
<cars>
 <color>red</color>
 <maxSpeed>120</maxSpeed>
 <age>2</age>
</cars>
<cars>
 <color>blue</color>
 <maxSpeed>100</maxSpeed>
 <age>3</age>
</cars>
<cars>
 <color>green</color>
 <maxSpeed>130</maxSpeed>
 <age>2</age>
</cars>

Native conversion of JSON to XML

If you don’t want to use any third-party libraries, then you can use this recursive function to convert JSON to XML:

function JSONtoXML(obj) {
  let xml = '';
  for (let prop in obj) {
    xml += obj[prop] instanceof Array ? '' : '<' + prop + '>';
    if (obj[prop] instanceof Array) {
      for (let array in obj[prop]) {
        xml += '\n<' + prop + '>\n';
        xml += JSONtoXML(new Object(obj[prop][array]));
        xml += '</' + prop + '>';
      }
    } else if (typeof obj[prop] == 'object') {
      xml += JSONtoXML(new Object(obj[prop]));
    } else {
      xml += obj[prop];
    }
    xml += obj[prop] instanceof Array ? '' : '</' + prop + '>\n';
  }
  xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
  return xml;
}

const jsonObj = {
  name: 'Garage',
  cars: [
    { color: 'red', maxSpeed: 120, age: 2 },
    { color: 'blue', maxSpeed: 100, age: 3 },
    { color: 'green', maxSpeed: 130, age: 2 },
  ],
};

const xml = JSONtoXML(jsonObj);

console.log(xml);

This code will produce the following output:

<name>Garage</name>

<cars>
<color>red</color>
<maxSpeed>120</maxSpeed>
<age>2</age>
</cars>
<cars>
<color>blue</color>
<maxSpeed>100</maxSpeed>
<age>3</age>
</cars>
<cars>
<color>green</color>
<maxSpeed>130</maxSpeed>
<age>2</age>
</cars>

3 Easy Ways to Make Any Text Bold in React

To make text bold in React, wrap the text with a span element, and set the fontWeight style property of the span to bold.

For example:

App.js

export default function App() {
  return (
    <div>
      Coding{' '}
      <span style={{ fontWeight: 'bold' }}>Beauty</span>
    </div>
  );
}
Making text bold in React

We used inline styles to make the text bold. The style attribute of a React element accepts a JavaScript object with camelCased properties instead of a CSS kebab-cased string. So, fontWeight sets the font-weight CSS property.

If we don’t need to control the boldness with a condition, then we can just wrap the text with a b element.

App.js

export default function App() {
  return (
    <div>
      Coding <b>Beauty</b>
    </div>
  );
}

Conditionally bold text with inline styles

Sometimes we might want to make a piece of text bold only if a certain condition is true. Here’s how we can do this:

App.js

import { useState } from 'react';

export default function App() {
  const [bold, setBold] = useState(false);

  const handleBoldChange = (event) => {
    setBold(event.target.checked);
  };

  return (
    <div>
      Coding{' '}
      <span
        style={{ fontWeight: bold ? 'bold' : 'normal' }}
      >
        Beauty
      </span>

      <br></br>

      <input
        name="bold"
        type="checkbox"
        value={bold}
        onChange={handleBoldChange}
      ></input>

      <label htmlFor="bold">Bold</label>
    </div>
  );
}
The text is bold only if the checkbox is checked.

We use a state variable named bold to store the current checked state of the checkbox and to determine whether the relevant text should be bold or not.

We attach an event listener to the onChange event, so it is called when the checkbox is checked or unchecked. In this listener, we use the setBold function to update the value of bold and change the boldness of the text.

Bold text with custom component

If we frequently need make text bold, we can abstract the logic into a reusable custom component.

App.js

function BoldText({ children }) {
  return (
    <span style={{ fontWeight: 'bold' }}>{children}</span>
  );
}

export default function App() {
  return (
    <div>
      Coding <BoldText>Beauty</BoldText>
    </div>
  );
}

This code will produce the same result on the web page.

Whatever text is place within the <BoldText> and </BoldText> tags will have a bold font.

Conditionally bold text with custom component

To make text bold conditionally with a custom component, we can create a boolean bold property that will determine whether the child text of the component should be bold or not.

App.js

import { useState } from 'react';

function BoldText({ children, bold }) {
  return (
    <span style={{ fontWeight: bold ? 'bold' : 'normal' }}>
      {children}
    </span>
  );
}

export default function App() {
  const [bold, setBold] = useState(false);

  const handleBoldChange = (event) => {
    setBold(event.target.checked);
  };

  return (
    <div>
      Coding <BoldText bold={bold}>Beauty</BoldText>

      <br></br>

      <input
        name="bold"
        type="checkbox"
        value={bold}
        onChange={handleBoldChange}
      ></input>

      <label htmlFor="bold">Bold</label>
    </div>
  );
}
The text is bold only if the checkbox is checked.

Bold text with class

Alternatively, we can make text bold in React by defining a bold class in a CSS file, e.g., App.css:

App.css

.bold {
  font-weight: bold;
}

We would then import the App.css file and apply the bold class to a span element to make all the text within it bold.

App.js

import './App.css';

export default function App() {
  return (
    <div>
      Coding <span className="bold">Beauty</span>
    </div>
  );
}

And this would produce exactly the same result as the previous two methods:

Conditionally bold text with class

Here’s how we would use a class name to make text bold only if a particular condition is true:

App.js

import { useState } from 'react';
import './App.css';

export default function App() {
  const [bold, setBold] = useState(false);

  const handleBoldChange = (event) => {
    setBold(event.target.checked);
  };

  return (
    <div>
      Coding{' '}
      <span className={bold ? 'bold' : ''}>Beauty</span>

      <br></br>

      <input
        name="bold"
        type="checkbox"
        value={bold}
        onChange={handleBoldChange}
      ></input>
      
      <label htmlFor="bold">Bold</label>
    </div>
  );
}

Using the ternary operator, we set the className property to the bold class if the bold variable is true. Otherwise, we set className to an empty string ('').

The text is bold only if the checkbox is checked.

Tip: Instead of the ternary operator, you can use the clsx utility from NPM to more easily construct class names from a set of conditions in React.

How to Create a Script Element in JavaScript

To create a script element in JavaScript:

  1. Use the document.createElement() method to create the script element.
  2. Set the src attribute on the element object to a script file.
  3. Include the script element in the HTML using the appendChild() method.

Consider this sample HTML markup:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body>
    <div id="box"></div>

    <script src="index.js"></script>
  </body>
</html>

Here’s how we can use JavaScript to create a script element in the HTML:

index.js

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

// use local file
// script.src = 'script.js';

script.src =
  'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js';

script.async = true;

// make code in script to be treated as JavaScript module
// script.type = 'module';

script.onload = () => {
  console.log('Script loaded successfuly');
  const box = document.getElementById('box');
  box.textContent = 'The script has loaded.';
};

script.onerror = () => {
  console.log('Error occurred while loading script');
};

document.body.appendChild(script);

The document.createElement() method creates an HTML element specified by the tag name and returns the element. By passing a script tag, we create a script element.

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

We set the src property on the script element to specify the script file to be loaded. We specify a remote file with a URL, but we could also specify a local file with a relative or absolute file path.

// use local file
// script.src = 'script.js';

script.src =
  'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js';

By setting the async property to true, the browser won’t have to load and evaluate the script before continuing to parse the HTML. Instead, the script file will be loaded in parallel to reduce delays and speed up the processing of the page.

script.async = true;

The type attribute indicates what type of script the file is. If it is a JavaScript module, we’ll need to set the type attribute to module to show this.

script.type = 'module';

For a complete list of all attributes supported by the script element, visit the MDN docs on the script element.

We listen for the onload event in order to perform an action when the script file has been loaded successfully.

script.onload = () => {
  console.log('Script loaded successfuly');
  const box = document.getElementById('box');
  box.textContent = 'The script has loaded.';
};

We listen for the onerror event so that we can perform a different action in case there was an error with loading the script.

script.onerror = () => {
  console.log('Error occurred while loading script');
};

The appendChild() method adds a DOM element as the last child of a specified parent element. By calling appendChild() on document.body, we add the script file to the body.

document.body.appendChild(script);
The script file is included in the body of the document.
The script file is included in the body of the document.

To add the script file to the head of the document instead, we can replace document.body with document.head.

document.head.appendChild(script);
The script file is included in the head of the document.
The script file is included in the head of the document.

How to Add Weeks to a Date in JavaScript

In this article, we’ll learn how to easily add any number of weeks to a Date object in JavaScript.

1. Date setDate() and getDate() methods

To add weeks to a Date in JavaScript:

  1. Use the getDate() method on the Date to get the day of the month of the Date.
  2. Add the result of getDate() to 7 multiplied by the number of weeks to add.
  3. Call the setDate() method with this sum as an argument.

For example:

function addWeeks(date, weeks) {
  date.setDate(date.getDate() + 7 * weeks);

  return date;
}

// May 20, 2022
const date = new Date('2022-05-20T00:00:00.000Z');

const newDate = addWeeks(date, 1);

// May 27, 2022
console.log(newDate); // 2022-05-27T00:00:00.000Z

Our addDays() function takes a Date object and the number of days to add as arguments, and returns the same Date object with the newly added days.

The Date getDate() method returns a number between 1 and 31 that represents the day of the month of the particular date.

The Date setDate() method changes the day of the month of the Date object to the number passed as an argument.

If the number you specify would change the month or year of the DatesetDate() automatically updates the Date information to reflect this.

function addWeeks(date, weeks) {
  date.setDate(date.getDate() + 7 * weeks);

  return date;
}

// May 20, 2022
const date = new Date('2022-05-20T00:00:00.000Z');

const newDate = addWeeks(date, 3);

// June 10, 2022
console.log(newDate); // 2022-06-10T00:00:00.000Z

Adding 3 weeks adds 21 days (20 + 21 = 41 days), but May has only 31 days, so the month is incremented by 1 and the day is set to 10 (41 – 31).

Avoid side effects

The setDate() method mutates the Date object it is called on. This introduces a side effect into our addDays() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setDate() on this copy, instead of the original.

function addWeeks(date, weeks) {
  const dateCopy = new Date(date);

  dateCopy.setDate(dateCopy.getDate() + 7 * weeks);

  return dateCopy;
}

const date = new Date('2022-05-20T00:00:00.000Z');

const newDate = addWeeks(date, 3);

console.log(newDate); // 2022-06-10T00:00:00.000Z

// Original not modified
console.log(date); // 2022-05-20T00:00:00.000Z

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns addWeeks() function

Alternatively, you can use the pure addWeeks() function from the date-fns NPM package to quickly add weeks to a Date. It works similarly to our addWeeks() function.

import { addWeeks } from 'date-fns';

const date = new Date('2022-05-20T00:00:00.000Z');

const newDate = addWeeks(date, 3);

console.log(newDate); // 2022-06-10T00:00:00.000Z

// Original not modified
console.log(date); // 2022-05-20T00:00:00.000Z

How to Remove a Query String From a URL in JavaScript

To remove a query string from a URL in JavaScript:

  1. Create a URL object from the URL string using the URL() constructor.
  2. Set the search property of the URL object to an empty string ('').
  3. Get the resulting URL with the toString() method of the URL object.
const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

urlObj.search = '';

const result = urlObj.toString();

console.log(result); // https://example.com/posts#hash

We can use the URL class to parse, construct, normalize, and encode URLs.

The URL() constructor returns a newly created URL object representing the URL string passed as an argument. URL objects have properties that allow us to easily read and modify the components of a URL.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.host); // example.com

console.log(urlObj.origin); // https://example.com

console.log(urlObj.protocol); // https:

The search property returns the query string of the URL, including the ? character. It doesn’t include the hash.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.search); // ?page=5&sort=desc

By setting search to an empty string (''), we remove the query string from the URL.

Remove query string along with hash from URL

To remove the hash of the URL along with the query string, also set the hash property to an empty string:

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

urlObj.search = '';
urlObj.hash = '';

const result = urlObj.toString();

console.log(result); // https://example.com/posts

The hash property returns the fragment identifier of the URL, including the # character.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.hash); // #hash

By setting hash to an empty string (''), we remove the hash from the URL along with the query string.

How to Remove an Element On Click in React

In this article, we’ll learn how to easily remove an element onclick in React, whether it’s in a list or it’s a standalone element.

Remove stand-alone element onclick in React

To remove a stand-alone element onclick:

  1. Store the visibility state in a state variable as a Boolean value, and use its value to conditionally render the element.
  2. Attach an event handler to the onClick event of the element.
  3. In the event handler, negate the value of the visibility state to remove the element from the DOM.

One example should make this clear:

import { useState } from 'react';

export default function App() {
  const [visible, setVisible] = useState(true);

  const removeElement = () => {
    setVisible((prev) => !prev);
  };

  return (
    <div>
      Click to remove element
      <br />
      {visible && (
        <button onClick={removeElement}>Remove</button>
      )}
    </div>
  );
}
Removing an element onclick in React

We use the useState() to create a state variable in the component. This hook returns an array of two variables, generally called state and setState. The state variable (visible) holds the current visibility state, and the setState function (setVisible) updates it.

const [visible, setVisible] = useState(true);

We set an event handler to the onClick event of the button, so when the button is clicked, the handler function will be called.

<button onClick={removeElement}>Remove</button>

In the handler function, we use the setState function for the visibility state to update the state.

const removeElement = () => {
  setVisible((prev) => !prev);
};

Instead of passing the negated value directly, we pass a callback function to setState that returns the negated value. This ensures that we always get the most recent state value.

Tip

React batches state changes for performance reasons, so the state may not be updated immediately after setState is called, in the order we might expect. This is why we always pass a function to setState when the new state is computed from the data of the previous state.

Remove element from list onclick

To remove an element from a list onclick:

  1. Attach an event handler to the onClick event of every element in the array representing the list.
  2. In the event handler for a particular element, call the filter() method on the array, specifying a condition that is true for every element in the array apart from the one to be removed.
  3. Use setState to update the state array with the result returned from filter().

For example:

import { useState } from 'react';

export default function App() {
  const [fruits, setFruits] = useState([
    'Orange',
    'Banana',
    'Apple',
  ]);

  const removeElement = (index) => {
    const newFruits = fruits.filter((_, i) => i !== index);
    setFruits(newFruits);
  };

  return (
    <div>
      {fruits.map((fruit, index) => (
        <div key={index}>
          <button
            onClick={() => removeElement(index)}
          >
            {fruit}
          </button>
          <br />
          <br />
        </div>
      ))}
    </div>
  );
}
Removing an element from a list onclick in React
Removing an element from a list onclick

With the map() method, we render a button for each element in the array. For each button, we attach an event handler that will call the removeElement() method, passing as an argument the index of the element that the button represents.

{fruits.map((fruit, index) => (
  <div key={index}>
    <button
      onClick={() => removeElement(index)}
    >
      {fruit}
    </button>
    <br />
    <br />
  </div>
))}

removeElement() removes an element by returning a condition from the filter() callback that is true only for elements in the array that don’t have the index passed to removeIndex(). Doing this excludes the element with that index from the array, so when the array state is updated, the button representing that element is no longer rendered.

const fruits = ['Orange', 'Banana', 'Apple'];

const newFruits = fruits.filter((_, index) => index !== 1);

console.log(newFruits); // [ 'Orange', 'Apple' ]

Note: don’t modify state directly in React

Trying to remove the element from the array by modifying it using a function like splice() will not work:

const removeElement = (index) => {
  // ⚠️ Mutating the array like this will not update the view
  fruits.splice(index, 1);
};

State is meant to be immutable in React, so we can’t update the array by mutating it. It has to be replaced with a new array returned from filter() for the view to update.

Remove object element from list onclick

We can also use this approach to remove an element represented by an object from a list onclick.

import { useState } from 'react';

export default function App() {
  const [fruits, setFruits] = useState([
    { id: 1, name: 'Orange' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Apple' },
  ]);

  const removeElement = (id) => {
    const newFruits = fruits.filter(
      (fruit) => fruit.id !== id
    );
    setFruits(newFruits);
  };

  return (
    <div>
      {fruits.map((fruit) => (
        <div key={fruit.id}>
          <button onClick={() => removeElement(fruit.id)}>
            {fruit.name}
          </button>
          <br />
          <br />
        </div>
      ))}
    </div>
  );
}

Instead of filtering by index, this time we filter by the id property to remove an item from the array and remove the element from the list in the DOM.

const fruits = [
  { id: 1, name: 'Orange' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Apple' },
];

const newFruits = fruits.filter((fruit) => fruit.id !== 2);

console.log(newFruits);
// [ { id: 1, name: 'Orange' }, { id: 3, name: 'Apple' } ]

How to Fix the “Component is missing template or render function” Warning in Vue

In this article, we’ll learn how to easily fix the “Component is missing template or render function” warning in Vue.

The "Component is missing template or render" function Vue error occurring.

Here are some possible causes of this warning:

  1. Rendering a component that has no template.
  2. Not passing the App component to the createApp() method.
  3. Using the result of app.component() to set a component for a Vue Router route.

We’ll go through each of them in this article.

1. Rendering a component that has no template

The “Component is missing template or render function” warning occurs when you import a component and add it to the markup, but the file of the component has no template tag. To fix it, add a template tag with a child element to the component file.

For example:

App.vue

<template>
  <div id="app">
    <post-list></post-list>
  </div>
</template>

<script>
import PostList from './components/PostList.vue';

export default {
  components: {
    'post-list': PostList,
  },
};
</script>

components/PostList.vue

// ⚠️ empty file

There will be a warning because PostList.vue is empty and doesn’t have a template tag.

Here’s how we can remove the warning:

components/PostList.vue

<template>
  <div></div>
</template>

2. Not passing the App component to the createApp() method

To fix the “Component is missing template or render function” warning in Vue, ensure that the createApp() method is called with the App component as an argument.

For example, the file that sets up your Vue app might look like this:

main.js

import { createApp } from 'vue';
import * as VueRouter from 'vue-router';
import Home from './HomePage.vue';

// ⚠️ don't pass {} to createApp()!
const app = createApp({});

const routes = [{ path: '/', component: Home }];

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
});

app.use(router);

app.mount('#app');

There will be a warning here because we passed an empty object ({}) to createApp() instead of a component object.

We can remove the warning in this case by importing the App component and passing it to createApp():

import { createApp } from 'vue';
import * as VueRouter from 'vue-router';
import Home from './HomePage.vue';

// import App component
import App from './App.vue';

// ✅ removed warning
const app = createApp(App);

const routes = [{ path: '/', component: Home }];

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
});

app.use(router);

app.mount('#app');

3. Using the result of app.component() to set a component for a Vue Router route

Instead of importing a component from a file, you might have chosen to create one with the component() method of the object returned by createApp().

import { createApp } from 'vue/dist/vue.esm-bundler';
import * as VueRouter from 'vue-router';
import App from './App.vue';

const app = createApp(App);

// app.component() returns the app instance, not a component
// object
const Home = app.component('HomePage', {
  template: '<div>Home</div>',
});

// ⚠️ don't set "component" to the app instance!
const routes = [{ path: '/', component: Home }];

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
});

app.use(router);

app.mount('#app');

When app.component() is called with a definition object (the 2nd argument), it returns the application instance to allow chaining calls.

To fix the “Component is missing template or render function” warning in this case, call the app.component() method again with only the component name as an argument, and use the component object returned to define a route for Vue Router.

import { createApp } from 'vue/dist/vue.esm-bundler';
import * as VueRouter from 'vue-router';
import App from './App.vue';

const app = createApp(App);

// first app.component() call defines component
app.component('HomePage', {
  template: '<div>Home</div>',
});

// ✅ fix: second app.component() call returns component object
const Home = app.component('HomePage');

// ✅ sets "component" to component object
const routes = [{ path: '/', component: Home }];

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
});

app.use(router);

app.mount('#app');

How to Create a Spinner With Bootstrap Vue

A spinner is used to indicate an ongoing process to the user. They are suitable for operations that don’t take very long to complete, and they help to enhance the responsiveness of an application. Read on to learn more about the Vue Bootstrap spinner component and the various customization options it provides.

The Boostrap Vue Spinner Component (b-spinner)

Boostrap Vue provides the b-spinner component for creating spinners. It starts spinning as soon as it has been rendered on the page.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner></b-spinner>
  </div>
</template>
The Bootstrap Vue Spinner component (b-spinner)

Border spinner

We can use the type prop to display a particular type of spinner. By default the type is set to border, which makes the spinner transparent and gives it a thick circle border.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner type="border"></b-spinner>
  </div>
</template>
A border spinner in Bootstrap Vue

Grow spinner

Alternatively, we can set type to grow to make the spinner repeatedly grow into view and fade out.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner type="grow"></b-spinner>
  </div>
</template>
A grow spinner in Bootstrap Vue

Spinner colors

b-spinner comes with a variant prop that lets us customize the color of the spinner. There are a bunch of values it can take, including primary, secondary, danger, warning, success, and info.

Here we create multiple border spinners with many different colors:

<template>
  <div
    id="app"
    class="text-center d-flex justify-content-between"
  >
    <b-spinner
      v-for="variant in variants"
      :key="variant"
      :variant="variant"
    ></b-spinner>
  </div>
</template>

<script>
export default {
  data() {
    return {
      variants: [
        'primary',
        'secondary',
        'danger',
        'warning',
        'success',
        'info',
      ],
    };
  },
};
</script>
Border spinner components with different color variants.

We can also customize the color of grow spinners with the variant prop:

<template>
  <div
    id="app"
    class="text-center d-flex justify-content-between"
  >
    <b-spinner
      v-for="variant in variants"
      :key="variant"
      :variant="variant"
      type="grow"
    ></b-spinner>
  </div>
</template>

<script>
export default {
  data() {
    return {
      variants: [
        'primary',
        'secondary',
        'danger',
        'warning',
        'success',
        'info',
      ],
    };
  },
};
</script>
Grow spinner components with different color variants.

For more color customization options we can set the color CSS property using inline styles.

<template>
  <div
    id="app"
    class="text-center m-3 d-flex justify-content-between"
  >
    <b-spinner style="color: orange"></b-spinner>
    <b-spinner style="color: blue"></b-spinner>
    <b-spinner style="color: #800080"></b-spinner>
    <b-spinner style="color: green"></b-spinner>
    <b-spinner style="color: red"></b-spinner>
    <b-spinner style="color: #424242"></b-spinner>
  </div>
</template>
Customizing spinner colors with inline CSS.

Spinner size

Setting the small prop to true on the b-spinner creates a spinner of a smaller size.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner small></b-spinner>
    <b-spinner
      type="grow"
      small
    ></b-spinner>
  </div>
</template>
Using the small prop of the Bootstrap Vue spinner component

For more size customization options, we can add some inline styles to customize the width and height CSS properties.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner
      style="width: 50px; height: 50px"
    ></b-spinner>
    <b-spinner
      type="grow"
      style="width: 50px; height: 50px"
    ></b-spinner>
  </div>
</template>
Customizing the size of the spinner with inline styles.

Spinner margin

We can add any of the Bootstrap Vue margin utility classes to a b-spinner to adjust its spacing. Here we use the ms-4 class from Bootstrap to add a left margin to the second spinner:

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-spinner></b-spinner>
    <b-spinner
      type="grow"
      class="ms-4"
    ></b-spinner>
  </div>
</template>
Adjusting spinner margin.

Spinner in button

One good use for a spinner is within a button, to indicate that an action is currently taking place.

<template>
  <div
    id="app"
    class="text-center"
  >
    <b-button variant="primary">
      <b-spinner small></b-spinner>
      Loading...
    </b-button>
  </div>
</template>
Using the Boostrap Vue spinner component in a button.

Here’s a more practical example of using spinners within buttons. When the button is clicked to save, it changes its text and shows the spinner to indicate the ongoing save operation (simulated with a timeout). Then it hides the spinner and changes the text again after the save.

<template>
  <div
    id="app"
    class="text-center m-3"
  >
    <b-button
      variant="primary"
      @click="save"
    >
      <b-spinner
        small
        v-if="status === 'saving'"
      ></b-spinner>
      {{ buttonText }}
    </b-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      status: 'unsaved',
    };
  },
  computed: {
    buttonText() {
      if (this.status === 'unsaved') return 'Save';
      else if (this.status === 'saving') return 'Saving';
      else return 'Saved';
    },
  },
  methods: {
    save() {
      this.status = 'saving';
      setTimeout(() => {
        this.status = 'saved';
      }, 2000);
    },
  },
};
</script>

We use the status data property to track the current save state, and we create a buttonText computed property to determine what the button label should be from status.

Using a spinner in a button.

Conclusion

A spinner is useful for indicating app operations in the process of being completed. In this article, we learned how to use the spinner component from Bootstrap Vue (b-spinner) to easily create and customize spinners.

How to Check if a String Contains Only Numbers in JavaScript

To check if a string contains only numbers in JavaScript, call the test() method on this regular expression: ^\d+$. The test() method will return true if the string contains only numbers. Otherwise, it will return false.

For example:

function containsOnlyNumbers(str) {
  return /^\d+$/.test(str);
}

console.log(containsOnlyNumbers('HTML5')); // false
console.log(containsOnlyNumbers('1234')); // true
console.log(containsOnlyNumbers('3 bananas')); // false

The RegExp test() method searches for a match between a regular expression and a string.

The / and / characters are used to start and end a regular expression.

The ^ character marks the beginning of the string input, and the $ character marks the end of it.

The \d pattern matches any digit (09) in the string.

Adding the + character after the \d makes the regex match one or more occurrences of the \d pattern.

So the regex matches a string that starts and ends with a consecutive sequence of digits.

We can use the [0-9] pattern to match digits. This pattern matches any number character between 0 and 9.

function containsOnlyNumbers(str) {
  return /^[0-9]+$/.test(str);
}

console.log(containsOnlyNumbers('HTML5')); // false
console.log(containsOnlyNumbers('1234')); // true
console.log(containsOnlyNumbers('3 bananas')); // false

You might find [0-9] to be more readable than \d, especially if you’re not very familiar with special characters in regular expressions.

Match a string that contains numbers separated by a character

Sometimes we would like to match strings where the numbers might be separated by a particular character, such as a space or comma.

function containsOnlyNumbers(str) {
  return /^(\d+,)*(\d+)$/.test(str);
}

console.log(containsOnlyNumbers('123456789')); // true (separator not required)
console.log(containsOnlyNumbers('123,456,789')); // true
console.log(containsOnlyNumbers('123-456-789')); // false

We do this using a regular expression of this format: ^(\d+{ch})*(\d+)$, where {ch} is the character separating the numbers.

So we can use a very similar regex to match a string that contains only numbers separated with hyphens:

function containsOnlyNumbers(str) {
  return /^(\d+-)*(\d+)$/.test(str);
}

console.log(containsOnlyNumbers('123456789')); // true
console.log(containsOnlyNumbers('123,456,789')); // false
console.log(containsOnlyNumbers('123-456-789')); // true

Or spaces:

function containsOnlyNumbers(str) {
  return /^(\d+ )*(\d+)$/.test(str);
}

console.log(containsOnlyNumbers('123456789')); // true
console.log(containsOnlyNumbers('123 456 789')); // true
console.log(containsOnlyNumbers('123-456-789')); // false

Tip: If you ever come across a regular expression with a pattern you find hard to understand, this regular expression cheat sheet from the MDN docs may help.

Like before, we could use [0-9] in place of \d for the regular expression:

function containsOnlyNumbers(str) {
  return /^([0-9]+-)*([0-9]+)$/.test(str);
}

console.log(containsOnlyNumbers('123456789')); // true
console.log(containsOnlyNumbers('123,456,789')); // false
console.log(containsOnlyNumbers('123-456-789')); // true