Categories
JavaScript Answers

How to Add Nested Routes with React Router Version 5?

If we use React to create our JavaScript app, we probably add a routing solution so that we can render different components if we go to different URLs.

React Router is a popular routing library to serve this purpose.

In this article, we’ll look at how to add nested routes with React Router version 5.

Add Nested Routes with React Router Version 5

We can nested routes with React Router version by nesting Route components inside the function we pass into the render prop.

To do this, we write:

import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";

const FrontPage = () => <p>front page</p>;
const HomePage = () => <p>home page</p>;
const AboutPage = () => <p>about page</p>;
const Backend = () => <p>back end</p>;
const Dashboard = () => <p>dashboard</p>;
const UserPage = () => <p>user page</p>;

export default function App() {
  return (
    <div>
      <BrowserRouter>
        <Link to="/">front page</Link>
        <Link to="/home">home page</Link>
        <Link to="/about">about page</Link>
        <Link to="/admin">back end</Link>
        <Link to="/admin/home">dashboard</Link>
        <Link to="/admin/users">user page</Link>
        <Route path="/" component={FrontPage} exact />
        <Route path="/home" component={HomePage} />
        <Route path="/about" component={AboutPage} />

        <Route
          path="/admin"
          render={({ match: { url } }) => (
            <>
              <Route path={`${url}/`} component={Backend} exact />
              <Route path={`${url}/home`} component={Dashboard} />
              <Route path={`${url}/users`} component={UserPage} />
            </>
          )}
        />
      </BrowserRouter>
    </div>
  );
}

We have the FrontPage , HomePage , AboutPage , Backend , Dashboard , and UserPage route components.

We’ll use the when we define our routes.

Then in App , we add the BrowserRouter component so we can add the routes inside it.

We add the Link component with the to prop to add links that goes to the given route.

Then we add Route components to map URL paths to components that are passed into the component prop.

The path prop lets us set the path of the route.

exact lets us only load the component when the exact path is matched.

When we go to the URL path given, then the given component will load.

The last Route component has the path set to '/admin' , which is the first part of the URL path.

The render prop is set to a function that takes an object with the match.url property.

We destructure that from the object, then pass them into the Route components we return in the function.

This lets us map route with the path starting with /admin to the given components.

So when we go to /admin , we see the Backend component displayed.

If we go to /admin/home , we see the Dashboard component rendered.

And if we go to /admin/users , we see the UserPage component rendered.

Therefore, when we click on the links, we see the content of each component displayed.

Conclusion

We can add nested routes with React Router 5 easily by nested Route components.

Categories
JavaScript Answers

How to Get the Start and the End of a Day in JavaScript?

Sometimes, we may want to get the start and end of a day with JavaScript.

In this article, we’ll look at ways to get the start and end of a day with JavaScript.

Using Native Date Methods

One way to get the start and end of a day with JavaScript is to use native date methods.

We can use the setHours method to set the hours of a day to the start or end of a day.

For instance, we can write:

const start = new Date(2020, 1, 1, 1, 1);
start.setHours(0, 0, 0, 0);
console.log(start)

We create the start date with the Date constructor.

Then we call setHours with all zeroes to set the time of the date to midnight.

So start is:

Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)

if we’re in Pacific time.

Likewise, we can use setHours to set the hours, minutes, seconds, and milliseconds to the end of the date.

To do this, we write:

const end = new Date(2020, 1, 1, 1, 1);
end.setHours(23, 59, 59, 999);
console.log(end)

to create a date and set it to the end of the date by passing in a few arguments.

23 is the hours.

The first 59 is the minutes.

The second 59 is the seconds.

And 999 is the milliseconds.

Therefore, end is:

Sat Feb 01 2020 23:59:59 GMT-0800 (Pacific Standard Time)

after calling setHours .

Using Moment.js

Alternatively, we can use the moment.js library to return the start and end of a date.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).startOf('day');
console.log(start.toString())

to create a moment object with the moment function with a JavaScript native date object as its argument.

Then we call startOf with 'day' to return a moment object with the time set to the start of the day.

So we get:

Sat Feb 01 2020 00:00:00 GMT-0800

as the value of start.toString() if we’re in the Pacific time zone.

Likewise, we can use the endOf method to get the end of the date.

To do this, we write:

const end = moment(new Date(2020, 1, 1, 1, 1)).endOf('day');
console.log(end.toString())

We call endOf instead of startOf .

And then end.toString() returns Sat Feb 01 2020 23:59:59 GMT-0800 if we’re in the Pacific time zone.

We can also convert the time zone to UTC before call startOf and endOf with the utc method.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).utc().startOf('day');
console.log(start.toString())

const end = moment(new Date(2020, 1, 1, 1, 1)).utc().endOf('day');
console.log(end.toString())

to do the conversion.

Then start.toString() returns:

Sat Feb 01 2020 00:00:00 GMT+0000

And end.toString() returns:

Sat Feb 01 2020 23:59:59 GMT+0000

Conclusion

We can get the start and end of a date with JavaScript with native date methods or moment.js.

Categories
JavaScript Answers

How to Get Clipboard Data When We Paste Data into an Element with JavaScript?

Sometimes, we may want to get the clipboard data that we paste into an element in our web app.

In this article, we’ll look at how to get clipboard data when we paste it into our JavaScript app.

Listen to the paste Event

The paste event is triggered when we paste data into an element.

Therefore, we can just listen to that event when our own event listener to get the pasted content.

For instance, we can write the following HTML:

<div id='editableDiv' contenteditable='true'>Paste</div>

Then we can write the following JavaScript code to listen to the paste event:

const handlePaste = (e) => {
  let clipboardData, pastedData;
  e.stopPropagation();
  e.preventDefault();
  clipboardData = e.clipboardData || window.clipboardData;
  pastedData = clipboardData.getData('text/plain');
  console.log(pastedData);
}
const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);

We create the handlePaste function to get the clipboard data.

First, we call stopPropagation to stop the propagation of the event to the parent and ancestor elements.

Then we call preventDefault to prevent the default paste behavior.

Then we can get the clipboard data from the e.clipboardData or window.clipboardData properties.

Next, we call getData with 'text/plain' to get the pasted text data.

And then we log the pastedData with console log.

Then we select the editable div with the getElementById method.

And we call addEventListener on the div to listen to the paste event.

We can simplify the function by calling e.clipboardData.getData to get the data directly.

Then we can call document.execCommand to do the pasting to the div.

To do this, we write:

const handlePaste = (e) => {
  const pastedText = e.clipboardData.getData('text/plain')
  console.log(pastedText)
  document.execCommand('insertText', false, pastedText);
  e.preventDefault();
}

const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);

We get the pasted text with:

e.clipboardData.getData('text/plain')

Then pastedText has what we pasted into the div.

Then we run:

document.execCommand('insertText', false, pastedText);

to insert the text by issuing the insertText command with the pastedText .

The rest of the code is the same.

Conclusion

We can listen to the paste event on an element and get the data from the event object of the paste event handler to get the data pasted into an element.

Categories
JavaScript Answers

How to Get the ID of the Clicked Element in the JavaScript Click Handler?

Sometimes, we want to get the ID of the element that we clicked on in the JavaScript click event handler.

In this article, we’ll look at how to get the ID of the clicked element in the JavaScript click handler.

Set the onclick Property of Each Element to the Same Event Handler Function

One way to let us get the ID of the element when we click on an element is to set the onclick property of each element object to the same click event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

Then we can write the following JavaScript code to set the event handler of each element to the same click event handler:

const onClick = function() {
  console.log(this.id, this.innerHTML);
}
document.getElementById('1').onclick = onClick;
document.getElementById('2').onclick = onClick;
document.getElementById('3').onclick = onClick;

The onClick function is the event handler for clicks of each button.

this is the element that we clicked on.

We can get the id property to get the ID of the element that’s clicked on.

And innerHTML has the button’s content.

Then we assign the onClick function as the value of the onclick property to each button element.

Therefore, when we click on the Button 1 button, we get:

'1' 'Button 1'

logged.

When we click on the Button 2 button, we get:

'2' 'Button 2'

And when we click on the Button 3 button, we get:

'3' 'Button 3'

logged.

Getting the Element Clicked on from the Event Object

Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

And the following JavaScript code:

const onClick = (event) => {
  console.log(event.srcElement.id);
}
window.addEventListener('click', onClick);

We call window.addEventListener to attach the click event listener to the html element.

Then we get the element that’s clicked on from the event.srcElement property.

And we can get the ID of that element with the id property.

We can replace event.srcElement with event.target :

const onClick = (event) => {
  console.log(event.target.id);
}
window.addEventListener('click', onClick);

and we get the same result.

We can also check if the element we clicked on is a button with the nodeName property.

For instance, we can write:

const onClick = (event) => {
  if (event.target.nodeName === 'BUTTON') {
    console.log(event.target.id);
  }
}
window.addEventListener('click', onClick);

to add an if statement to check if event.target.nodeName is 'BUTTON' before running the console.log method.

This way, we only run the click handler code if we clicked on a button.

Conclusion

We can get the ID of the element that’s clicked from the click event handler.

We can either get the value from this if we use a regular function.

Or we can get the same value from the event object of the click event handler.

Categories
JavaScript Answers

How to the Number of Seconds to a Time String in the hh:mm:ss Format with JavaScript?

Sometimes, we may want to convert the number of seconds elapsed to a time string in the hh:mm:ss format in our JavaScript app.

In this article, we’ll look at how to convert the number of seconds to a time string in hh:mm:ss format.

Create Our Own Function

We can create our own function to convert the number of seconds elapsed to a time string in hh:mm:ss format.

For instance, we can write:

const toHHMMSS = (numSecs) => {
  let secNum = parseInt(numSecs, 10);
  let hours = Math.floor(secNum / 3600).toString().padStart(2, '0');
  let minutes = Math.floor((secNum - (hours * 3600)) / 60).toString().padStart(2, '0');;
  let seconds = secNum - (hours * 3600) - (minutes * 60).toString().padStart(2, '0');;
  return `${hours}:${minutes}:${seconds}`;
}

console.log(toHHMMSS(1234))

In the toHHMMSS function, we parse the numSecs parameter into a number.

Then we compute the hours by dividing secNum by 3600.

Then we round it down to the nearest integer with Math.floor .

Then we call toString on it to convert it into a string.

And then we call padStart to pad the number string to 2 digits with a leading zero if necessary.

To compute the minutes , we subtract secNum by the hours multiplied by 3600 and divide the whole thing by 60.

We get the minutes after subtracting the hours.

And we round the number down to the nearest integer with Math.floor .

Then we pad it into a 2 digit string with padStart also.

Next, we compute the seconds by subtracting the hours and minutes converted to seconds from secNum .

Then we convert it to a string and call padStart on it to pad the string to 2 digits with a leading zero if necessary.

And finally, we return the hours , minutes , and seconds in a string.

Therefore, the console log should log:

'00:20:34'

Date.prototype.toISOString

We can call toISOString on the JavaScript date object to get a date string with the hours, minutes, and seconds.

To get the elapsed time, we just create a date with timestamp 0, then call setSeconds to set the timestamp to the elapsed seconds.

And then we can all toISOString to get the date string and extract the hours, minutes, and seconds part of the returned date string.

For instance, we can write:

const date = new Date(0);
date.setSeconds(1234);
const timeString = date.toISOString().substr(11, 8);
console.log(timeString)

We create a Date instance with timestamp 0.

Then we call setSeconds to set the seconds of the time.

And then we call toISOString to get a date string.

Then we call substr to extract the hours, minutes, and seconds substring.

Therefore, timeString is:

'00:20:34'

Conclusion

We can use math, date, and string methods to get the elapsed seconds into hh:mm:ss format easily with JavaScript.