Search code examples
cssreactjsreact-bootstrapbootstrap-grid

Save React-Bootstrap xs,sm,md,lg,xl spans/offsets into css class


We have the following <Row> with 2 <Col> elements as such:

<Row>
    <Col xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={5} xl={4}>
        <h3 className='graph-header-1'>First Header</h3>
        <div>Graph that fills the col-width goes here</div>
    </Col>
    <Col xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={{ span: 5, offset: 1 }} xl={{ span: 4, offset: 2 }}>
        <h3 className='graph-header-1'></h3>
        <div>2nd Graph that fills the column's width goes here</div>
    </Col>
</Row>

This layout (row with 2 cols, with these specific spans / offsets for each of xs,sm,md,lg,xl) will be used in a few places in our app. Is it possible to save this in a class so that, rather than setting these values over and over again, we simply use:

<Row className='our-responsive-layout'>
    <Col>
        <h3 className='graph-header-1'>First Header</h3>
        <div>Graph that fills the col-width goes here</div>
    </Col>
    <Col>
        <h3 className='graph-header-1'></h3>
        <div>2nd Graph that fills the column's width goes here</div>
    </Col>
</Row>

...where our-responsive-layout is a class that handles the spans / offsets for the 2 columns? Alternatively, having a class for each column (rather than 1 class for the row for the 2 columns) would be helpful as well.

Edit: if there are any thorough guides on handling responsiveness in a complex react-app using react-bootstrap and their container / row / column components, please share. I am worried that adding things like xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={{ span: 5, offset: 1 }} xl={{ span: 4, offset: 2 }} throughout our app with make the code much messier.

Thanks!


Solution

  • Why don't you simply create a component for this ? something like that (demo) :

    import React, { Component } from "react";
    import { render } from "react-dom";
    
    const App = () => {
      return (
        <MyRow>
          <MyCol>Here is your col 1</MyCol>
          <MyCol>Here is your col 2</MyCol>
        </MyRow>
      );
    };
    
    const MyRow = ({children}) => {
      return <div className='this is your row'>{children}</div>
    }
    
    const MyCol = ({children}) => {
      return <div className='this is your col'>{children}</div>;
    }
    
    render(<App />, document.getElementById("root"));
    
    

    Here you just replace div tags (and the className of course) in MyRow and MyCol with your rows and col components and it should be enough.

    If you want to add or change classes on a col for example, you can just add an prop.