By Tari Ibaba
/ Last updated on September 29, 2022
1. Date setDate() and getDate() methods
To subtract 30 days from the current date in JavaScript:
Use the Date() constructor to create a new Date object with the current date.
Call the getDate() method on this object to get the days.
Subtract 30 from the return value of getDate().
Pass the result of the subtraction to the setDate() method.
// Current date: September 29, 2022const date = newDate();
date.setDate(date.getDate() - 30);
// New date: August 30, 2022console.log(date);
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 days you specify would change the month or year of the Date, setDate() automatically updates the Date information to reflect this.
// April 25, 2022const date = newDate('2022-04-25T00:00:00.000Z');
date.setDate(40);
// May 10, 2022console.log(date); // 2022-05-10T00:00:00.000Zconsole.log(date.getDate()); // 10
April has only 30 days, so passing 40 to setDate() here increments the month by one and sets the day of the month to 10.
2. date-fns subDays() function
Alternatively, we can use the subDays() function from the date-fns NPM package to subtract 30 days from the current date. subDays() takes a Date object and the number of days to subtract as arguments. It returns a new Date object with the days subtracted.
import { subDays } from'date-fns';
// Current date: September 29, 2022const date = newDate();
const newDate = subDays(date, 30);
// New date: August 30, 2022console.log(newDate);
Note that subDays() returns a new Date object without mutating the one passed to it.
With the useState() hook we create a state variable (message) to store the current value of the input field. We also create another state variable (updated) that will be updated with the input field value when the button is clicked.
We set an onChange event handler on the input field to make this handler get called whenever the input value changes. In the handler, we use the event.target property to access the object representing the input element. The value property of this object contains the input value, so we pass it to setMessage() to update message, and this reflects on the page.
After setting up the controlled input, we can now use message outside the handleChange handler to access the current value of the input field.
So in the onClick event handler we set on the button, we use setUpdated(message) to update the updated variable with the current input field value.
Get value of uncontrolled input on button click
To get the value of an uncontrolled input on button click in React:
Create a ref for the input field
Set an onClick event handler on the button.
Use the ref object to access the current input value in the event handler.
While the data in a controlled input is handled by React state, the data in an uncontrolled input is handled by the DOM itself. This is why the input in the example above doesn’t have a value prop or onChange event handler set. Instead, we access the input field value with a React ref. The DOM updates this value when the text in the input is changed.
We create a ref object with the useRef() hook and set it to the ref prop of the input. Doing this sets the current property of the ref object to the DOM object that represents the input element.
useRef() returns a mutable ref object that does not change value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState().
Although the React documentation recommends using controlled components, uncontrolled components offer some advantages. You might prefer them if the form is very simple and doesn’t need instant validation, and values only need to be accessed when the form is submitted.
To fix the “cannot find name ‘describe'” error, install the type definitions for your testing framework, and then add the definitions to the types array in your tsconfig.json file.
This error happens if you try to use the describe() function in a TypeScript file, but type definitions for the package are missing.
index.tsCopied!
/* Cannot find name 'it'. Do you need to install type
definitions for a test runner? Try
`npm i --save-dev @types/jest` or
`npm i --save-dev @types/mocha`. ts(2582) */describe('example', () => {
it('adds two numbers together', () => {
expect(2 + 2).toBe(4);
});
});
Install the type definitions for the testing framework you’re using by running one of the following commands at the root of your project directory.
ShellCopied!
# Jest
npm i -D @types/jest jest
# Mocha
npm i -D @types/mocha mocha
# Yarn# Jest
yarn add --dev @types/jest jest
# Mocha
yarn add --dev @types/mocha mocha
Add typings to types array in tsconfig.json
In some cases, this is all you need to fix the error. But if it persists, you might need to add the newly installed typings to the types array of your tsconfig.json file.
So if you’re using Jest, you’ll add a jest string to the types array, and then your tsconfig.json file will look something like this:
tsconfig.jsonCopied!
{"compilerOptions":{"types":[// ... other types"jest"]// ..other settings}}
If you’re using Mocha too, you’ll add a mocha string to the types array.
tsconfig.jsonCopied!
{"compilerOptions":{"types":[// ... other types"mocha"]// ..other settings}}
Include test files
If the error still doesn’t go away after doing this, make sure that TypeScript is not ignoring the directory containing your test files.
If you’ve set the include array in your tsconfig.json file, make sure the patterns specified in this array match the directory where your test files are located.
For example, if your test files are located in a src directory, TypeScript will detect them with a configuration like this:
tsconfig.jsonCopied!
{"compilerOptions":{},"include":["src/**/*"],}
But if they’re located in a tests directory, we’ll need to add an additional glob pattern to make TypeScript detect them:
If you’ve set the exclude array in your tsconfig.json file, make sure that none of the patterns in the array match the directory containing the test files, as this will prevent TypeScript from detecting them.
For example, in the tsconfig.json file below, files ending with .spec.ts have been excluded, so TypeScript will ignore them and the error will occur when you attempt to use describe() in them.
We used the addEventListener() method to add a handler for the click event to the #box element. This event handler will be called whenever the user clicks the box.
In the handler function, we called the remove() method on the element to remove it from the DOM.
We could also have used the target property on the event object passed to the handler to remove the element.
We can use the event object to access useful information and perform certain actions related to the event. For the click event, the target property lets us access the DOM element that was clicked.
Removing the element with the target property is useful when we want to dynamically remove many elements onclick. For example:
index.html
<!DOCTYPE html><htmllang="en"><head><title>Coding Beauty Tutorial</title><linkrel="stylesheet"href="index.css" /></head><body>
Click on a box to remove it.
<divclass="container"><divclass="box"id="box-1"></div><divclass="box"id="box-2"></div><divclass="box"id="box-3"></div></div><scriptsrc="index.js"></script></body></html>
This is because the target property returns the innermost element in the DOM that was clicked. This is in contrast to the event.currentTarget property, which returns the element that the event listener was added to.
To link a local image in React, import the image at the top of the file and assign it to the src prop of an img element.
For example:
App.js
// import image from fileimport myImage from'./my-image.jpg';
exportdefaultfunctionApp() {
return (
<div>
{/* show image */}
<imgsrc={myImage}alt="Trees"height="200" /><br /><spanstyle={{color: 'green',
fontSize: '1.2em',
fontWeight: 'bold',
}}
>
Trees
</span></div>
);
}
This approach works when using a Webpack-based tool like Create React App.
Note that the image file must be within the project directory to be imported successfully. An error will occur if the file is outside the project directory.
Link image in React with require() function
Alternatively, we can use the require() function to link an image in React.
The following code example will produce precisely the same result on the page as the first example.
The advantage require() has here is that it doesn’t need to be at the top of the page. We can simply assign the result of require() to the src prop without having to store it in a variable.
Link image in public folder
Another way to link an image in React is to place it in the public folder and reference it with its relative path.
For example, if we placed the my-image.png file in the public folder, we’ll be able to display it in the page like this:
Using the public folder is advantageous when we have many images that we want to display dynamically.
In the following examples, we dynamically display 100 images placed in a grid subfolder under public, and named with a certain pattern (image-1.jpg, image-2.jpg, …, image-100.png) in a grid.
Call the getFullYear() method on the Date to get the year.
Subtract the years.
Pass the result of the subtraction to the setFullYear() method.
For example:
functionsubtractYears(date, years) {
date.setFullYear(date.getFullYear() - years);
return date;
}
// Feb 20, 2022const date = newDate('2022-02-20T00:00:00.000Z');
const newDate = subtractYears(date, 3);
// Feb 20, 2019console.log(newDate); // 2019-02-20T00:00:00.000Z
Our subtractYears() function takes a Date object and the number of years to subtract as arguments. It returns the same Date object with the years subtracted.
The Date getFullYear() method returns a number that represents the year of a particular Date.
The Date setFullYear() method sets the year of a Date to a specified number.
Avoid side effects
The setFullYear() method mutates the Date object it is called on. This introduces a side effect into our subtractYears() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setFullYear() on this copy, instead of the original.
functionsubtractYears(date, years) {
// make copy with "Date" constructorconst dateCopy = newDate(date);
dateCopy.setFullYear(date.getFullYear() - years);
return dateCopy;
}
const date = newDate('2022-02-20T00:00:00.000Z');
const newDate = subtractYears(date, 3);
// Feb 20, 2019console.log(newDate); // 2019-02-20T00:00:00.000Z// Original not modifiedconsole.log(date); // 2022-02-20T00:00:00.000Z
Tip: 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 subYears() function
Alternatively, we can use the subYears() function from the date-fns NPM package to quickly subtract years from a Date. It works like our pure subtractYears() function.
import { subYears } from'date-fns';
const date = newDate('2022-02-20T00:00:00.000Z');
const newDate = subYears(date, 3);
// Feb 20, 2019console.log(newDate); // 2019-02-20T00:00:00.000Z// Original not modifiedconsole.log(date); // 2022-02-20T00:00:00.000Z
First, we create a new Vue instance ref by setting the inputref prop to a value (name).
<inputref="name"placeholder="Name"
/>
After doing this, we are able to access the $refs property of the Vue instance to access the object that represents the input element. We then call the focus() method on this object to set focus on the input.
this.$refs.name.focus();
We set the focusInput() method as a handler for the click event of the Focus button. So when the button is clicked, focusInput() is called and the input gains focus.
<button @click="focusInput">Focus</button>
Set focus on custom input component
Custom input components are useful for abstracting logic built around an input element and for reusing an input element styled in a particular way.
For custom components, calling focus() on its ref object will cause an error. For it to work, we’ll need to add a focus() method to the custom component that calls the focus() method of its root input element.
Now we can set focus on the custom input component when the button is clicked.
Set focus on input after page load
To give the input focus immediately after the page loads, we can call the focus() method from the mounted lifecycle hook of the Vue instance with the input ref. The mounted method is called after a component is added to the DOM, which happens when a page is loading.
There are scenarios where we’ll need to wait for the DOM to be updated before calling focus() to give the input element focus.
For example, we might be using a boolean variable to determine whether an input element should be present in the DOM or not.
Because Vue batches state updates, the input element might not be added to the DOM immediately, and we won’t be able to access its ref right away.
We can use the nextTick() instance method to ensure that the DOM has been updated to include the input after modifying the boolean variable before calling focus().
<template><divid="app"><!-- conditional rendering with "v-if" directive --><inputv-if="showInput"ref="name"placeholder="Name"
/><br /><br /><button @click="focusInput">Show and focus</button></div></template><script>exportdefault {
data() {
return {
showInput: false,
};
},
methods: {
focusInput() {
// Set boolean variable to show inputthis.showInput = true;
this.$nextTick(() => {
// This callback will only be called after the// DOM has been updatedthis.$refs.name.focus();
});
},
},
};
</script>
Set focus on next input after Enter press
Let’s say we have multiple input elements that need to be filled on the page. We could improve the UX by focusing on the succeeding text input when the user presses the Enter key to signify that they are done with filling in one input.
We do this by assigning a listener to the keypress event on the first input. Because of the enter event modifier, the event listener is only called when a key is pressed and the key is Enter.
We create a ref for the second input, and in the keypress.enter event listener we call the focus() method on the ref object to set focus on the second input.
Here’s what the home page of this web app will look like:
You can see that there is a hash character (#) before the index path (/) in the URL of the page. This happens because Vue Router uses hash history mode to represent the URLs of different routes. In hash mode, a hash character is placed before the route path, and this prevents the page from reloading when a Router link is clicked.
The createRouter() function from vue-router creates a Router instance to be used by the Vue app. We can pass an object with a bunch of options to the function to customize the behavior of the router.
Setting the history option to the result of the createWebHistory() function from vue-router switches the router from hash history mode to HTML5 history mode. This removes the hash from the URLs.
Remove hash from URL in Vue 2 and Vue Router 3
Vue 2 apps use Vue Router 3, so the Router initialization logic will differ.
Your main.js file might look like this at the moment:
Here we use a VueRouter() constructor to create a new router instance. Like createRouter(), we can pass a set of options to customize its behavior. To change from hash history mode to HTML5 history mode and remove the hash from the URLs, set the mode option to 'history'.
By Tari Ibaba
/ Last updated on September 18, 2022
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:
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:
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.
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:
functiongetMonthShortName(monthNo) {
const date = newDate();
date.setMonth(monthNo - 1);
// Use the browser's default localereturn date.toLocaleString([], { month: 'short' });
}
console.log(getMonthShortName(1)); // Janconsole.log(getMonthShortName(2)); // Febconsole.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:
functiongetTwoConsecutiveMonthNames(monthNumber) {
const date1 = newDate();
date1.setMonth(monthNumber - 1);
const date2 = newDate();
date2.setMonth(monthNumber);
const formatter = newIntl.DateTimeFormat('en-US', { month: 'short' });
// Format both dates with the same locale and optionsconst firstMonth = formatter.format(date1);
const secondMonth = formatter.format(date2);
return`${firstMonth} & ${secondMonth}`;
}
console.log(getTwoConsecutiveMonthNames(1)); // Jan & Febconsole.log(getTwoConsecutiveMonthNames(2)); // Feb & Marconsole.log(getTwoConsecutiveMonthNames(3)); // Mar & Apr
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.
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.
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.
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 ('').
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.