question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React Responsive doesn't work if i refresh the page

See original GitHub issue

React Responsive doesn’t work while on mobile

When i working on next.js project from desktop. I open the mobile preview mode and in there have no problem, but if i refresh my page in preview mode react-responsive doesn’t work, thats why in production doesn’t work

Example Use;

index.js

export default function Home({ logs, version, texts }) {
  const isTablet = useMediaQuery({ query: "(max-width: 1024px)" });

  return (
    <>
      <Box height="8px" background="#107c41"></Box>
      <SimpleGrid columns={isTablet ? 1 : 2}>
        <Infos texts={texts} version={version} logs={logs} />
        <Upload texts={texts} />
      </SimpleGrid>
    </>
  );

upload.js

export default function Upload(props) {
  const value = useContext(ItemStore)
  const { colorMode } = useColorMode();
  const [isUpload, setIsUpload] = useState(false);
  const isTablet = useMediaQuery({ query: "(max-width: 1024px)" });
  const isMobileXL = useMediaQuery({ query: "(max-width: 600px)" });
  const toast = useToast();

  function handleFile(file) {

    if (!file)
      return toast({
        title: "File upload failed",
        status: "warning",
        position: "top-left",
        isClosable: true,
      });

    if (!file.type === excel && !file.type === csv)
      return toast({
        title: "Wrong file type",
        status: "error",
        position: "top-left",
        isClosable: true,
      });

    switch (file.type) {
      case excel:
        readXlsxFile(file).then((rows) => {
          value.setvalue(rows);
        });
        setIsUpload(true);
        break;

      case csv:
        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
          value.setvalue(
            fileReader.result
              .toString()
              .split("\n")
              .map((e) => e.trim())
              .map((e) => e.split(",").map((e) => e.trim()))
          );
        };
        setIsUpload(true);
        break;

      default:
        toast({
          title: "Wrong file type",
          status: "error",
          position: "top-left",
          isClosable: true,
        });
        break;
    }
  }

  return (
    <Box
      padding={(isTablet ? "0rem" : "4rem") && (isMobileXL ? "1rem" : "4rem")}
      paddingTop={isTablet ? "0rem" : null}
      borderLeft={isMobileXL ? "0" : "1px solid gray"}
    >
      <Text
        color={colorMode === "light" ? "#107c41" : "white"}
        fontSize={(isTablet ? "xl" : "2xl") && (isMobileXL ? "md" : "2xl")}
      >
        <InfoIcon mr="0.5rem" /> {props.texts.uploadlayer}
      </Text>
      <Collapse in={isUpload} animateOpacity>
        <Button
          mt="2"
          _focus="none"
          onClick={() => {
            value.setvalue(null);
            setIsUpload(false);
            document.getElementsByClassName("docs").value = null;
          }}
          size={isMobileXL ? "sm" : "md"}
          leftIcon={<DeleteIcon />}
          colorScheme="green"
          display="block"
          w="100%"
        >
          Delete
        </Button>
      </Collapse>
      <FormControl
        borderRadius="0.5rem"
        border="2px dashed gray"
        mt="3"
      >
        <FormLabel
          color={colorMode === "light" ? "#107c41" : "white"}
          p="1rem"
          fontWeight="bold"
          fontSize={isMobileXL ? "md" : "2xl"}
        >
          {isUpload ? <CheckIcon /> : <DownloadIcon />} Upload your file
        </FormLabel>
        <Input
          className="docs"
          onChange={(e) => handleFile(e.target.files[0])}
          type="file"
          opacity="0"
          accept=".xlsx, .csv"
          border="0px"
        />
      </FormControl>
      {value.value
        ? value.value
            .slice(1)
            .map((element, index) => (
              <Result key={index} label={value.value[0]} items={element} />
            ))
        : null}
    </Box>
  );
}

For better explain;

When i without refresh open preview mode

image

But if I refresh page in preview mode it looks like this;

image

My package.json;

{
  "name": "invoice-printer-next",
  "version": "0.1.1",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@chakra-ui/core": "^0.8.0",
    "@chakra-ui/icons": "^1.0.6",
    "@chakra-ui/react": "^1.3.4",
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.1.5",
    "framer-motion": "^3.10.2",
    "gray-matter": "^4.0.2",
    "jsonwebtoken": "^8.5.1",
    "next": "10.0.8",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-markdown": "^5.0.3",
    "react-youtube": "^7.13.1",
    "read-excel-file": "^5.0.0"
  },
  "devDependencies": {
    "react-responsive": "^8.2.0"
  }
}

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:7
  • Comments:8

github_iconTop GitHub Comments

12reactions
amcclure-supercommented, Apr 17, 2021

I was able to fix the issue by disabling ssr on import:

import dynamic from "next/dynamic"
const MediaQuery = dynamic(() => import("react-responsive"), {
  ssr: false
})
9reactions
buudicommented, Apr 10, 2021

I have the same issue in next-js any solutions?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Bug with React: component not rendering until page is refreshed
If I have the Box component and switch to the Carousel component it doesn't work until I refresh the page but if I...
Read more >
Responsive code is buggy on resizing, works on refresh - GSAP
I got it cleaned up and working now, but the animation fires instantly now every time the page loads or is resized. When...
Read more >
Handling common JavaScript problems - MDN Web Docs
Note: The easiest solution is to declare the iteration variable with let instead of var —the value of i associated with the function...
Read more >
Concurrent UI Patterns (Experimental) - React
For example, if we switch from one page to another, and none of the code or ... That's how we tell React we...
Read more >
react-responsive - npm
You can use the onChange callback to specify a change handler that will be called when the media query's value changes. import React...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found