React: How to make <td> collapse as column in a <tr> in mobile view

Viewed 481

I'm trying to make my websites look consistent across devices.

I have a table that looks like this: table desktop view

How can I make the same table behave so that when viewed on mobile, the <td> in a <tr> will sort in a column order with the <th> next to every table data like this: table mobile view

I am making the website in React so if there is a way of doing this in React that I am not aware of, the better

3 Answers

was able to do this with media queries:

/* set for mobile breakpoint */
@media (max-width: 1024px) {
    /* display th for desktop only, hide on mobile */
    .desktop {
        display: none;
    }
    
    /* arranges td as column in the tr */
    .mobile-flex {
        display: flex;
        width: 100%;
    }

    /* adds faux-headers on each td by reading "data-header" attribute of the td*/
    td:before {
    content: attr(data-header);
    display: block;
    font-weight: bold;
    margin-right: 10px;
    max-width: 110px;
    min-width: 110px;
    word-break: break-word;
    }
}
<table>
  <thead>
    <tr>
      <th class="desktop">Title</th>
      <th class="desktop">Author</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="mobile-flex" data-header="Title">Sample book title 1</td>
      <td class="mobile-flex" data-header="Author">Sample author name 1</td>
    </tr>
    <tr>
      <td class="mobile-flex" data-header="Title">Sample book title 2</td>
      <td class="mobile-flex" data-header="Author">Sample author name 2</td>
    </tr>
  </tbody>
</table>

Media queries would probably not be effective here as you are looking to change the actual html. You'll probably want to use a package such as https://www.npmjs.com/package/react-breakpoints to render different content depending on whether it is a desktop or mobile device.

Use a single class and make your table responsive

@media (max-width: 576px) {
  .tbl-responsive th {
    display: none;
  }

  .tbl-responsive td {
    display: flex;
  }

  .tbl-responsive td .btn{
    position: relative;
    left: -10px;
  }

  .tbl-responsive td:before {
    content: attr(data-header);
    font-weight: bold;
    color: #000;
    margin-right: 10px;
  }
}
<table class="tbl-responsive">
  <thead>
    <tr>
      <th>Title</th>
      <th>Author</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-header="Title: ">Sample book title 1</td>
      <td data-header="Author">Sample author name 1</td>
    </tr>
    <tr>
      <td data-header="Title: ">Sample book title 2</td>
      <td data-header="Author: ">Sample author name 2</td>
    </tr>
  </tbody>
</table>

Related