Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react use media query

//i used bootstrap carousel where i dynamically changed its height for mobile.
import Carousel from 'react-bootstrap/Carousel';
import 'bootstrap/dist/css/bootstrap.min.css';
import {useState, useEffect} from 'react';

function MyCarousel() {

  const [carouselHeight,setCarouselHeight] = useState("500px");

  const img_style = { //style constant used to set carousel height below
      height: carouselHeight,
  }

  useEffect( () => {  //this useEffect Hook will trigger only once when this component is mounted (loaded) to DOM
      if(window.innerWidth <= 382){
        setCarouselHeight("200px");
      }
  })

  return (
    <Carousel fade style={img_style}>
      <Carousel.Item>
        <img
          style={img_style}
          className="d-block w-100"
          src="images/carousel1.jpg"
          alt="First slide"
        />
        <Carousel.Caption>
          <h3>First slide label</h3>
          <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
        </Carousel.Caption>
      </Carousel.Item>
      <Carousel.Item>
        <img
          style={img_style}
          className="d-block w-100"
          src="images/carousel2.jpg"
          alt="Second slide"
        />

        <Carousel.Caption>
          <h3>Second slide label</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </Carousel.Caption>
      </Carousel.Item>
      <Carousel.Item>
        <img
          style={img_style}
          className="d-block w-100"
          src="images/carousel3.jpg"
          alt="Third slide"
        />

        <Carousel.Caption>
          <h3>Third slide label</h3>
          <p>
            Praesent commodo cursus magna, vel scelerisque nisl consectetur.
          </p>
        </Carousel.Caption>
      </Carousel.Item>
    </Carousel>
  );
}

export default MyCarousel;
 
PREVIOUS NEXT
Tagged: #react #media #query
ADD COMMENT
Topic
Name
5+4 =