Search code examples
javascriptcssreactjsresponsive-designmedia-queries

Set initial const based on viewport width react js


I'm building a photo gallery in react js and various values (thumbnail size, image size) have to change based on the width of the viewport. The values that need to change are the basis of various calculations in the application so can't simply be put in a stylesheet. Without wishing to get bogged down in the inner workings of the thing I set the initial values in my render method like so:

    // vars
    const thumbWidth = 75;
    const viewWindowWidth = thumbWidth * 5;
    const thumbContainerwidth = thumbWidth * 5;
    const thumbContainerHeight = 75;        

    let thumbContainerWidth = this.state.photos.length * thumbWidth; 
    let thumbContainerPos = this.state.thumbContainerPos;

    let dynamicStyles = {
        thumbContainerOuter : {
            width: thumbContainerwidth
        },
        thumbContainerInner : {
            left: thumbContainerPos
        } 
    }

What I want to do is make the thumbWidth value larger if the vp size is larger and for it to base out at 75 beneath, say, 480px (or other arbitrary value).

The approach I've tried thus far probably reflects my relative newness to react js, I include the following at the start of the component:

if(window.innerWidth >= 480 ) {
   const thumbWidth = 75;
} else {
   const thumbWidth = 100;
}

Unfortunately, doing this means that react flags up 'thumbWidth' as undefined wherever it is used subsequently.

The same happens if I include it in componentDidMount or in the render method itself.

I've looked at node packages such as contra/react-responsive but these seem to be about enclosing jsx in media queries which doesn't solve the issue. Am I just doing something really silly or is this a tricky one to sort out?


Solution

  • const is blocked-scope so declaring it inside an if won't make it available outside of the if block. You could either declare let thumbWidth in a higher scope or just use a ternary expression :

    const thumbWidth = window.innerWidth >= 480 ? 75 : 100