Liv Stan
Liv Stan

Reputation: 429

How can I set dynamically set props depending on the screen width?

I have the below code where I have a component that is a carousel of slides (from the library nuka-carousel). I would like the property slideWidth={0.5} to be slideWidth={1} when the screen width is below a certain level (729px) so that when the screen gets smaller, rather than seeing more than one slide at a time you can only see one.

I have tried using media queries but I couldn't find a way to set the property depending on the styling.

import React from 'react'
import Carousel from 'nuka-carousel'

class Quotes extends React.Component {

  state = {
    slideIndex: 0,
  };

  render() {

    return (
      <Carousel slideWidth={0.5}>
         {this.props.slides.map(slide => (
             <Slide>
                .... Content ....
             </Slide>
         ))}
      </Carousel>
    )
  }
};

Has anyone had this problem before or can think of a solution?

Thanks!

Upvotes: 1

Views: 786

Answers (1)

James South
James South

Reputation: 604

you can use the matchMedia API which is like media queries for JS - you can set one up with your breakpoint and change JS variables which will allow you to, say, conditionally render your carousel like you want:

var mediaQueryList = window.matchMedia('(min-width: 729px)');

    return (
      { mediaQueryList.matches && //matches
        <Carousel slideWidth={0.5}>
         {this.props.slides.map(slide => (
             <Slide>
                .... Content ....
             </Slide>
         ))}
        </Carousel>
      }
      { !mediaQueryList.matches && //doesn't match
        <Carousel slideWidth={1}>
         {this.props.slides.map(slide => (
             <Slide>
                .... Content ....
             </Slide>
         ))}
        </Carousel>
      }
    )

so here the idea is that when the MQ matches we render the 0.5 carousel and when it doesn't match, we render the 1 carousel. you can also set up a callback and control the value of a variable if you want:

function handleWidthChange(evt) {
  if (evt.matches) {
    /* The viewport is currently wide */
    myVariable = 0.5;
  } else {
    /* The viewport is currently narrow */
    myVariable = 1;
  }
}
mediaQueryList.addListener(handleWidthChange); // Add the callback function as a listener to the query list.

handleWidthChange(mediaQueryList);//call it

    return (
        <Carousel slideWidth={ myVariable }>
         {this.props.slides.map(slide => (
             <Slide>
                .... Content ....
             </Slide>
         ))}
        </Carousel>

    )

Upvotes: 1

Related Questions