determining window width in a React app

I am currently working on a project where I need to conceal certain components when the screen reaches a particular breakpoint. To achieve this, I plan to save the screen width in a state variable and toggle the display property to "none" when it falls below the designated breakpoint.

My main query is related to accessing the screen width or viewport width in React. Additionally, I am wondering if this approach is considered optimal for creating responsive designs?

Answer №1

Here is a straightforward illustration

const utilizeFullWindow = (size) => {
  const [width, setWidth] = useState(0)
  
  useEffect(() => {
    function adjustWindowSize() {
      setWidth(window.innerWidth)
    }
    
    window.addEventListener("resize", adjustWindowSize)
    
    adjustWindowSize()
    
    return () => { 
      window.removeEventListener("resize", adjustWindowSize)
    }
  }, [setWidth])
  
  return useFullWindow > size
}

and how to implement it,

const Salutation = () => {
  const expanded = utilizeFullWindow(600)
  return (<h1>{expanded ? "Greetings Earthlings" : "Hi there"}</h1>)
}

There are various hooks in the following resources that may enhance your understanding.

  1. changeWindowSize,
  2. useWindowSize, https://github.com/jaredLunde/react-hook/tree/master/packages/window-size

Answer №2

To retrieve the width, use the following method:

const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

Alternatively, CSS can be used to hide specific elements at different breakpoints and create responsive layouts.

Answer №3

After realizing a mistake in the previous response, I found a better approach that worked smoothly:

const detectScreenWidth = (size) => {
const [width, setWidth] = useState(0)

useEffect(() => {
  function handleResize() {
    setWidth(window.innerWidth)
  }
  
  window.addEventListener("resize", handleResize)
  
  handleResize()
  
  return () => { 
    window.removeEventListener("resize", handleResize)
  }
}, [setWidth])

return width

}

const screenWidth = detectScreenWidth(400)
<h1>{screenWidth >= 500 ? "Desktop" : "Mobile"}</h1>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The horizontal scrollbar is not displaying

(RESOLVED) Currently, I am developing a movie app that displays film titles through an Accordion feature using Bootstrap. Specifically, I have created an Accordion that showcases movies added to a favorites list. The intention is for this favorites secti ...

Mithril does not automatically refresh the view

After modifying the prop values in Mithril, the view is not automatically redrawn. To update my prop upon pressing a button, I use the following code: something.vm.test(something.vm.test() + 1); Although this code updates the prop value, the changes ...

What is the best way to arrange these containers in a horizontal stack?

Check out the code snippet at: https://codepen.io/shayaansiddiqui/pen/YzGzeOj I'm looking to align these boxes horizontally, how can I achieve that? <div> <div class="container"> <img src="#" ...

Dynamic Hero Banner

As I work on creating a basic website for my football team, I am facing an issue with the text placement in different screen sizes. While the Jumbotron background image resizes perfectly according to the screen size, the text outside of the Jumbotron doesn ...

What is the method for adjusting the background color of the Material-UI AppBar component?

I am in the process of developing an application utilizing Material-UI components and have customized the color scheme in the theme as shown below (in src/index.js): const theme = createMuiTheme({ palette: { pale: { main: '#FCF4D9', ...

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

There seems to be an issue with Next.js retrieving an image from an external localhost

I'm facing a challenge in my current Next.js 14 project where I am encountering an issue when attempting to display an image from localhost:8081 using the Image component from 'next/image'. The backend is written in Java and it sends the ima ...

Flipping the Script: Unraveling Bootstrap 4's Reverse Pull

Why isn't pull-right or pull-left working, and what am I doing wrong? The code in question <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh ...

In a Typescript Next Js project, the useReducer Hook cannot be utilized

I'm completely new to Typescript and currently attempting to implement the useReducer hook with Typescript. Below is the code I've written: import { useReducer, useContext, createContext } from "react" import type { ReactNode } from &q ...

The pinFileToIPFS method in Pinata IPFS is currently unable to accept files uploaded by users

Currently, I am immersed in a project where I am utilizing React.js, Express.js, and Node.js to transform a user-provided image into an NFT on the Ethereum blockchain. To achieve this, I must first upload the image to IPFS (Pinata being my choice of servic ...

Identify whether the application is built with nextJS, react, or react-native

I'm currently developing a library for React applications and I anticipate that certain features will function differently depending on the environment. I am seeking a method to identify whether the current environment is a ReactJS application (creat ...

Get the maximum width in pixels through JavaScript when it is specified in different units within the CSS

I'm looking to retrieve the max-width value in px from CSS for use in a JavaScript code. The challenge is that this value might be specified in different units in the CSS file. Any suggestions on how to achieve this using JavaScript? const element = ...

Mastering the art of using transitions in conjunction with display properties

I'm trying to achieve a fade-in effect with the CSS property display:block. Here's my HTML code: <div>Fade</div> And here's my CSS code: div { display: none; transition: 2s; } div:hover { display: block; } Unfortunately, thi ...

What is the best way to pass the image source as a prop to a child component in React?

I have created a reusable component that includes a title, image, and onPress function. However, the image is not being rendered or displayed properly. Can someone please advise me on how to pass the image source dynamically? Is there a method to reference ...

Highlighting a row upon being clicked

How can I implement a feature in my HTML page that highlights a row when selected by changing the row color to #DFDFDF? If another row is selected, I would like the previously selected row to return to its original color and the newly selected row to be h ...

Enhance Your HTML Table Layout with Dual Column Borders

Can I increase the space between columns while still keeping borders on both sides? Check out the illustration below: ...

Styling and structuring your website with CSS and HTML

I am coding an HTML page where I've incorporated CSS for the styling. However, I'm facing an issue with the drop-down menu. Whenever I try to click on a drop-down option, it disappears. How can I fix this? I want the drop-down options to be clic ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

What is the method for obtaining source code from GitHub?

I am looking to reproduce this website or get it up and running: . It is available as open source at https://github.com/securingsincity/react-ace, but despite my efforts, I have not been able to successfully run it on my local machine What steps should I ...

Error message when using TypeScript with useState hook in React for a string value within an

Hello fellow developers I am facing a Type error issue Apologies for the confusion, let me clarify my question Error in Code interface IInfo { name: string; password: string; } useState Declaration const [info, setInfo] = useState<IInfo>({ ...