最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check for Windowsize React component - Stack Overflow

programmeradmin0浏览0评论

What I am basically trying to create is a navbar that has two pletely different html hierarchy based on the window size. I want it to be different for mobile than for a desktop version. eg a nav bar that is on the right on desktop and one that is on the top for mobile.

A simply state of what was doing. I created a const that would use a state of the screen size. I had used the useState() to get a default for now but I know that if I was first loading on desktop and it it was defaulted to mobile. I would have to resize first to get the desktop version instead.

const [sizeState, setSizeState] = useState("mobile");
const changeNavbar = () => {
    if (window.innerWidth <= 900) {
        setSizeState("mobile"); 
    } else {
        setSizeState("desktop"); 
    }
};

window.addEventListener('resize', changeNavbar);

the sizeState would then call an if function determines what state it currently is set to.

if (sizeState === "mobile") {
    return ( //some code for mobile) }
else {
// return some code for desktop
 }

for now it always returns the mobile version even if loading upon a innerwidth that is above 900 abd only on resize it would do something.

I have been trying to use a onload stuff and an eventlistener that would listen to load. but i cant manage to call the changeNavbar function on the first load of the page.

I saw people remending to use useMediaQuery but I don't know how to get it to work based on my if (mediaquery is set to md) { return( mobile navbar) }

If someone could help me use the useMediaQuery in this instead of my previous attempt, so that I can have two separated returns I would also be soooooo thankful for the help!

What I am basically trying to create is a navbar that has two pletely different html hierarchy based on the window size. I want it to be different for mobile than for a desktop version. eg a nav bar that is on the right on desktop and one that is on the top for mobile.

A simply state of what was doing. I created a const that would use a state of the screen size. I had used the useState() to get a default for now but I know that if I was first loading on desktop and it it was defaulted to mobile. I would have to resize first to get the desktop version instead.

const [sizeState, setSizeState] = useState("mobile");
const changeNavbar = () => {
    if (window.innerWidth <= 900) {
        setSizeState("mobile"); 
    } else {
        setSizeState("desktop"); 
    }
};

window.addEventListener('resize', changeNavbar);

the sizeState would then call an if function determines what state it currently is set to.

if (sizeState === "mobile") {
    return ( //some code for mobile) }
else {
// return some code for desktop
 }

for now it always returns the mobile version even if loading upon a innerwidth that is above 900 abd only on resize it would do something.

I have been trying to use a onload stuff and an eventlistener that would listen to load. but i cant manage to call the changeNavbar function on the first load of the page.

I saw people remending to use useMediaQuery but I don't know how to get it to work based on my if (mediaquery is set to md) { return( mobile navbar) }

If someone could help me use the useMediaQuery in this instead of my previous attempt, so that I can have two separated returns I would also be soooooo thankful for the help!

Share Improve this question edited Apr 15, 2023 at 14:02 marc_s 757k184 gold badges1.4k silver badges1.5k bronze badges asked May 10, 2022 at 19:32 tj_shmttj_shmt 611 silver badge3 bronze badges 1
  • 1 Does this answer your question? Get viewport/window height in ReactJS – Gavin Holmes Commented May 10, 2022 at 19:47
Add a ment  | 

2 Answers 2

Reset to default 4
  1. You can simply implement it using styled-ponents and styled-breakpoints packages and its hooks API.

    Here is an example: https://codesandbox.io/s/styled-breakpoints-n8csvf

import { down } from "styled-breakpoints";
import { useBreakpoint } from "styled-breakpoints/react-styled";

export default function App() {
  const isMobile = useBreakpoint(down("sm"));

  return (
    <div className="App">
      {isMobile ? "Mobile View" : "Desktop View"}
    </div>
  );
}

  1. Or you can create custom hooks like this: https://github./jasonjin220/use-window-size-v2

import useWindowSize from "use-window-size-v2";

export default function App() {
  const { width, height } = useWindowSize();

  return (
    <div className="box">
      <h1>useWindowSize Hook</h1>
      <p>
        height: {height}
        <br />
        width: {width}
      </p>
    </div>
  );
}

You can to use a simple hook like that:

import { useCallback } from 'react';

export const useAddEventListener = () => {
  const addEventListener = useCallback((
        target: HTMLElement | Window,
        eventKey: string,
        event: (e: Event) => void
    ) => {
        target.addEventListener(eventKey, event);
        return () => target.removeEventListener(eventKey, event);
    }, []);
  return { addEventListener };
};

And then call it:

const { addEventListener } = useAddEventListener();
addEventListener(window, 'resize', (e) { 
    console.log(window.innerWidth);
})
发布评论

评论列表(0)

  1. 暂无评论