Categories
React Answers

How to get the scroll position with React?

Sometimes, we want to get the scroll position with React.

In this article, we’ll look at how to get the scroll position with React.

How to get the scroll position with React?

To get the scroll position with React, we create our own hook.

For instance, we write

import { useEffect, useState } from "react";

export const useWindowScrollPositions = () => {
  const [scrollPosition, setPosition] = useState({ scrollX: 0, scrollY: 0 });

  useEffect(() => {
    const updatePosition = () => {
      setPosition({ scrollX: window.scrollX, scrollY: window.scrollY });
    };

    window.addEventListener("scroll", updatePosition);
    updatePosition();

    return () => window.removeEventListener("scroll", updatePosition);
  }, []);

  return scrollPosition;
};

to listen to the window scroll event with addEventListener.

We set updatePosition as the event listener.

In it, we get the x coordinate of the scroll position with window.scrollX.

And we get the x coordinate of the scroll position with window.scrollY .

We call setPositiion with an object with the values to update scrollPosition.

We remove the event listener with removeEventListener when the component unmounts.

Then we use it by writing

import { useWindowScrollPositions } from "path/to/useWindowScrollPositions";

export const MyComponent = () => {
  const { scrollX, scrollY } = useWindowScrollPositions();

  return (
    <div>
      Scroll position is ({scrollX}, {scrollY})
    </div>
  );
};

We call useWindowScrollPositions to return an object with the scroll coordinates.

Conclusion

To get the scroll position with React, we create our own hook.

Categories
React Answers

How to fix ReferenceError: document is not defined with Next.js and JavaScript?

Sometimes, we want to fix ReferenceError: document is not defined with Next.js and JavaScript.

In this article, we’ll look at how to fix ReferenceError: document is not defined with Next.js and JavaScript.

How to fix ReferenceError: document is not defined with Next.js and JavaScript?

To fix ReferenceError: document is not defined with Next.js and JavaScript, we check if document is defined.

For instance, we write

if (typeof document === "undefined") {
  // ...
} else {
  // ...
}

in our component to check if document is undefined with typeof document === "undefined".

If it’s not defined, then we render items on server side.

Otherwise, we render client side components.

Categories
React Answers

How to implement media queries with React?

Sometimes, we want to implement media queries with React.

In this article, we’ll look at how to implement media queries with React.

How to implement media queries with React?

To implement media queries with React, we create our own hook.

For instance, we write

const useMediaQuery = (query) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    window.addEventListener("resize", listener);
    return () => window.removeEventListener("resize", listener);
  }, [matches, query]);

  return matches;
};

export default useMediaQuery;

to create the useMediaQuery hook.

In it we check if the media query matches the screen size with window.matchMedia.

Then we call setMatches if media.matches is different from matches.

We then call addEventListener to listen to the resize event with listener.

And we call removeEventListener if matches or query changes.

Then we call useMediaQuery in our component to see if our screen matches the media query string.

Conclusion

To implement media queries with React, we create our own hook.

Categories
React Answers

How to call JavaScript function from another file in React?

Sometimes, we want to call JavaScript function from another file in React.

In this article, we’ll look at how to call JavaScript function from another file in React.

How to call JavaScript function from another file in React?

To call JavaScript function from another file in React, we export the function we want to call and then import it.

For instance, we write

export const plusSlides = (n) => {
  showSlides((slideIndex += n));
};

in slideShow.js.

Then we write

import { plusSlides } from "./slideShow";

//...

const Comp = () => {
  //...
  const handleClick = (event) => {
    plusSlides(1);
  };
  //...
};

to import the plusSlides function from the slideShow.js file.

And then we call it in the handleClick function.

Conclusion

To call JavaScript function from another file in React, we export the function we want to call and then import it.

Categories
React Answers

How to change the URL in react-router v4 without using Redirect or Link with JavaScript?

Sometimes, we want to change the URL in react-router v4 without using Redirect or Link with JavaScript.

In this article, we’ll look at how to change the URL in react-router v4 without using Redirect or Link with JavaScript.

How to change the URL in react-router v4 without using Redirect or Link with JavaScript?

To change the URL in react-router v4 without using Redirect or Link with JavaScript, we call the history.push method.

For instance, we write

this.props.history.push("/foo");

to call history.push with '/foo' to navigate to /foo.

Conclusion

To change the URL in react-router v4 without using Redirect or Link with JavaScript, we call the history.push method.