Categories
JavaScript Answers

How to force reloading a page when using browser back button with JavaScript?

Sometimes, we want to force reloading a page when using browser back button with JavaScript.

In this article, we’ll look at how to force reloading a page when using browser back button with JavaScript.

How to force reloading a page when using browser back button with JavaScript?

To force reloading a page when using browser back button with JavaScript, we watch the pageshow event.

For instance, we write

window.addEventListener("pageshow", (event) => {
  const historyTraversal =
    event.persisted ||
    (typeof window.performance != "undefined" &&
      window.performance.navigation.type === 2);

  if (historyTraversal) {
    window.location.reload();
  }
});

to call window.addEventListener to watch for the 'pageshow' event.

In the event listener, we check if we navigated with

const historyTraversal =
  event.persisted ||
  (typeof window.performance != "undefined" &&
    window.performance.navigation.type === 2);

If that’s true, then we call window.location.reload to reload the page.

Conclusion

To force reloading a page when using browser back button with JavaScript, we watch the pageshow event.

Categories
JavaScript Answers

How to match any character that is not a letter or number with a regular expression in JavaScript?

Sometimes, we want to match any character that is not a letter or number with a regular expression in JavaScript.

In this article, we’ll look at how to match any character that is not a letter or number with a regular expression in JavaScript.

How to match any character that is not a letter or number with a regular expression in JavaScript?

To match any character that is not a letter or number with a regular expression in JavaScript, we can use the [^a-zA-Z0-9] regex pattern.

For instance, we write

let str = "dfj,dsf7lfsd .sdklfj";
str = str.replace(/[^A-Za-z0-9]/g, " ");

to call str.replace with the /[^A-Za-z0-9]/g regex to replace all non alphanumeric characters with spaces.

Conclusion

To match any character that is not a letter or number with a regular expression in JavaScript, we can use the [^a-zA-Z0-9] regex pattern.

Categories
JavaScript Answers

How to parse JSON to receive a Date object in JavaScript?

Sometimes, we want to parse JSON to receive a Date object in JavaScript.

In this article, we’ll look at how to parse JSON to receive a Date object in JavaScript.

How to parse JSON to receive a Date object in JavaScript?

To parse JSON to receive a Date object in JavaScript, we call JSON.parse with our own parsing function.

For instance, we write

const dateTimeReviver = (key, value) => {
  let a;
  if (typeof value === "string") {
    a = /\/Date\((\d*)\)\//.exec(value);
    if (a) {
      return new Date(+a[1]);
    }
  }
  return value;
};

const obj = JSON.parse(jsonString, dateTimeReviver);

to create the dateTimeReviver functon that checks if the value being parsed is a string with

typeof value === "string"

Then we get the parts that has /\/Date\((\d*)\)\// pattern in it with exec.

If it’s found, then we create a Date object from it.

Otherwise, we return value as is.

Then we call JSON.parse with the jsonString we want to parse and the dateTimeReviver function that we created to parse the JSON string with the dates.

Conclusion

To parse JSON to receive a Date object in JavaScript, we call JSON.parse with our own parsing function.

Categories
React Answers

How to make React component/div draggable?

Sometimes, we want to make React component/div draggable.

In this article, we’ll look at how to make React component/div draggable.

How to make React component/div draggable?

To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.

For instance, we write

import React, { useRef, useState, useEffect } from "react";

const quickAndDirtyStyle = {
  width: "200px",
  height: "200px",
  background: "yellow",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
};

const DraggableComponent = () => {
  const [pressed, setPressed] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      ref.current.style.transform = `translate(${position.x}px, ${position.y}px)`;
    }
  }, [position]);

  const onMouseMove = (event) => {
    if (pressed) {
      setPosition({
        x: position.x + event.movementX,
        y: position.y + event.movementY,
      });
    }
  };

  return (
    <div
      ref={ref}
      style={quickAndDirtyStyle}
      onMouseMove={onMouseMove}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
    >
      <p>draggable</p>
    </div>
  );
};

export default DraggableComponent;

to check if the div is pressed with the onMouseDown and onMouseUp props.

If pressed is true, then we’re pressing on the div.

When the mouse is moving and pressed is true, then the setPosition function in onMouseMove is called.

In the useEffect callback, we watch the position value and set the transform style of the div as we drag the div.

The ref is set to the div with the ref prop.

Conclusion

To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.

Categories
JavaScript Answers

How to compare only date in moment.js and JavaScript?

Sometimes, we want to compare only date in moment.js and JavaScript.

In this article, we’ll look at how to compare only date in moment.js and JavaScript.

How to compare only date in moment.js and JavaScript?

To compare only date in moment.js and JavaScript, we can use the isAfter method.

For instance, we write

const isAfter = moment("2022-10-20").isAfter("2022-01-01", "year");

to call isAfter on the moment("2022-10-20") moment object to see if '2022-01-01' is after moment("2022-10-20") in terms of year.

It returns false since '2022-10-20' isn’t after '2022-01-01' in terms of year.

Conclusion

To compare only date in moment.js and JavaScript, we can use the isAfter method.