Search code examples
reactjstwitter-bootstrapreact-bootstrap

Change grid layout at breaking points with react-bootstrap


I want to create a grid view for 12 images in react bootstrap. In md and above, the images should be arranged 6x2 (6 on top, 6 on bottom) For sm and above, it should be 2x6 for xs it should be 1x12

but there does not appear to be such a grid feature within bootstrap and react bootstrap does not provide a useBreakpoint or similar tool to get the current screen size.

So is there an elegant way to make this happen? Dynamically change the grid layout based on boostrap breakpoints?


Solution

  • Bootstrap's grid view row and col are implemented using flex-box and it does support bootstrap's breakpoint system which are supported by react-bootstrap as well. (Unless you are talking about display: grid which all related css properties are not supported by Bootstrap)

    For example, col-sm-6 applies col-6 to sizes sm or above. Consider a div with col-12 col-sm-6 col-md-2 breakpoints: For sizes that size >= md it will be applied col-2, for sizes that sm <= size < md it will be applied col-6, and for sizes that size < sm it will be applied col-12.

    In react-bootstrap responsive grids they are written in this way:

    <Row>
        <Col xs={12} sm={6} md={2}>
            1
        </Col>
        <Col xs={12} sm={6} md={2}>
            2
        </Col>
        ...
    </Row>
    

    Which is same as native Bootstrap:

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="row">
      <div class="col-12 col-sm-6 col-md-2">
        1
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        2
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        3
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        4
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        5
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        6
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        7
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        8
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        9
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        10
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        11
      </div>
      <div class="col-12 col-sm-6 col-md-2">
        12
      </div>
    </div>