Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- Modified from React Pagination on https://codepen.io/sohmet13/pen/EpYZjR -->

<div id="app"></div>
              
            
!

CSS

              
                .mdl-table-search {
  margin-top: 10px;
  
  #search-label:after {
    background-color: rgb(255, 64, 129) !important;
  }

  .pagination {
    display: flex;
    list-style: none;
    cursor: pointer;
    justify-content: flex-end;

    li {
      background: #eeeeee;
      padding: 4px 0;
      width: 30px;
      text-align: center;
      margin-left: 5px;
      box-shadow: rgba(0, 0, 0, 0.14) 1px 1px 2px 0px, rgba(0, 0, 0, 0.2) 0px 2px 1px -5px, rgba(0, 0, 0, 0.12) 0px 1px 5px 0px;

      &.active {
        background: darkturquoise;

        a {
          color: #ffffff;
        }        
      }
    }
  }
}

.sort {
  position: absolute;
  right: 10px;
  bottom: 14px;
  cursor: pointer;

  &:before {
    position: absolute;
    right: 2px;
    width: 0;
    height: 0;
    padding: 0;
    content: "";
    border-left: 3px solid transparent;
    border-right: 3px solid transparent;
    pointer-events: none;
    bottom: 8px;
    border-bottom: 6px solid rgba(0,0,0,.12);
  }

  &:after {
    position: absolute;
    right: 2px;
    width: 0;
    height: 0;
    padding: 0;
    content: "";
    border-left: 3px solid transparent;
    border-right: 3px solid transparent;
    pointer-events: none;
    bottom: 0;
    border-top: 6px solid rgba(0,0,0,.12);
  }

  &.sort-asc {
    &:before {
      border-bottom-color: rgba(0,0,0,.5);
    }
  }

  &.sort-desc {
    &:after {
      border-top-color: rgba(0,0,0,.5);
    }
  }
}

              
            
!

JS

              
                class SearchTable extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: props.data,
      currentData: props.data,
      pageOfItems: []
    }
    this.sorted = props.details.reduce((accum, item) => {
      accum[item.name] = null
      return accum
    }, {})
    this.onChangePage = this.onChangePage.bind(this)
    this.search = this.search.bind(this)
    this.sort = this.sort.bind(this)
  }

  onChangePage(pageOfItems) {
    // update state with new page of items
    this.setState({ pageOfItems })
  }

  search(e) {
    let search = e.target.value.toLowerCase()
    let filter = item => {
      for (let key in item) {
        if (this.props.details.map(i => i.name).includes(key) && item[key].toString().toLowerCase().includes(search)) {
          return item
        }
      }
    }
    let data = this.state.data.filter(filter)
    this.setState({
      currentData: (data.length > 0) ? data : [{}]
    })
  }

  sort(e) {
    let value = e.target.id || e.target.parentNode.id
    let isSorted = this.sorted[value]
    let direction = isSorted ? 1 : -1
    let sort = (a, b) => {
      if (typeof a[value] === 'number' && typeof b[value] === 'number') {
        {
          if (a[value] > b[value]) { return direction }
          if (a[value] < b[value]) { return direction * -1 }
          return 0
        }
      } else {
        {
          if (a[value].toLowerCase() > b[value].toLowerCase()) { return direction }
          if (a[value].toLowerCase() < b[value].toLowerCase()) { return direction * -1 }
          return 0
        }
      }
    }
    
    this.sorted[value] = !isSorted
    let sorted = this.state.currentData.slice().sort(sort)
    let sortedData = this.state.data.slice().sort(sort)
    this.setState({
      data: sortedData,
      currentData: sorted
    }) 
  }

  render() {
    return (
      <main className="mdl-cell mdl-cell--8-col mdl-cell--2-offset">
        <div className="mdl-table-search mdl-cell mdl-cell--12-col mdl-grid mdl-grid--no-spacing">
          <div className="mdl-cell mdl-cell--3-col">
            <Search search={this.search}/>
          </div>
          <div className="mdl-cell mdl-cell--9-col">
            <Pagination items={this.state.currentData} onChangePage={this.onChangePage}/>
          </div>
        </div>
        <div id="mdl-table mdl-cell mdl-cell--12-col">
          {
            this.state.pageOfItems && Object.keys(this.state.pageOfItems[0] || {}).length !== 0 &&
            <table className="mdl-data-table mdl-js-data-table mdl-shadow--2dp mdl-cell mdl-cell--12-col">
              <HeadTable details={this.props.details} sort={this.sort} sortCheck={this.sorted}/>
              <tbody>
                {
                  this.state.pageOfItems.map((a, index) => 
                    <tr key={index} id={a.id}>
                      {
                        this.props.details.map((item, i) => {
                          return (
                            <td className="mdl-data-table__cell--non-numeric" key={`${a[item.name]}_${index}_${i}`}>
                              { a[item.name] }
                            </td>
                          )
                        })
                      }
                    </tr>
                  )
                }
              </tbody>
            </table>
          }
          {
            !(this.state.pageOfItems && Object.keys(this.state.pageOfItems[0] || {}).length !== 0) &&
            <table className="mdl-data-table mdl-js-data-table mdl-shadow--2dp mdl-cell mdl-cell--12-col">
              <tbody className="mdl-data-table__cell--non-numeric">
                <tr><td className="mdl-data-table__cell--non-numeric">No results found</td></tr>
              </tbody>
            </table>
          }
        </div>
      </main>
    )
  }
}

class Search extends React.Component {
  render() {
    return (
      <div className="mdl-textfield mdl-js-textfield">
        <input className="mdl-textfield__input" onKeyUp={this.props.search} type="text" id="search-input" />
        <label className="mdl-textfield__label" htmlFor="search-input" id="search-label">Search...</label>
      </div>
    )
  }
}

class HeadTable extends React.Component {
  render() {
    return (
      <thead>
        <tr id='headTable'>
          {
            this.props.details.map(item => {
              return (
                <th className="mdl-data-table__cell--non-numeric" key={item.name} id={item.name} onClick={this.props.sort} style={{ width: `${100 / this.props.details.length}%`}}>
                  <i className={`sort ${this.props.sortCheck[item.name] ? 'sort-desc' : this.props.sortCheck[item.name] === null ? '' : 'sort-asc'}`}></i> { item.display }
                </th>
              )
            })
          }
        </tr>
      </thead>
    )
  }
}

class Pagination extends React.Component {
  static defaultProps = {
    initialPage: 1,
    pageSize: 5
  }

  constructor(props) {
    super(props)
    this.state = { pager: {} }
  }

  componentWillMount() {
    // set page if items array isn't empty
    if (this.props.items && this.props.items.length) {
      this.setPage(this.props.initialPage)
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // reset page if items array has changed
    if (this.props.items !== prevProps.items) {
      this.setPage(this.props.initialPage)
    }
  }

  setPage(page) {
    const { items, pageSize } = this.props
    let pager = this.state.pager

    if (page < 1 || page > pager.totalPages) {
      return
    }
    // get new pager object for specified page
    pager = this.getPager(items.length, page, pageSize)
    // get new page of items from items array
    const pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1)
    // update state
    this.setState({ pager: pager })
    // call change page function in parent component
    this.props.onChangePage(pageOfItems)
  }

  getPager(totalItems, currentPage, pageSize) {
    // default to first page
    currentPage = currentPage || 1

    // calculate total pages
    const totalPages = Math.ceil(totalItems / pageSize)

    let startPage, endPage
    if (totalPages <= 10) {
      // less than 10 total pages so show all
      startPage = 1
      endPage = totalPages
    } else {
      // more than 10 total pages so calculate start and end pages
      if (currentPage <= 6) {
        startPage = 1
        endPage = 10
      } else if (currentPage + 4 >= totalPages) {
        startPage = totalPages - 9
        endPage = totalPages
      } else {
        startPage = currentPage - 5
        endPage = currentPage + 4
      }
    }

    // calculate start and end item indexes
    const startIndex = (currentPage - 1) * pageSize
    const endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1)

    // create an array of pages to ng-repeat in the pager control
    const pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i)

    // return object with all pager properties required by the view
    return {
      totalItems,
      currentPage,
      pageSize,
      totalPages,
      startPage,
      endPage,
      startIndex,
      endIndex,
      pages
    }
  }

  render() {
    const pager = this.state.pager

    if (!pager.pages || pager.pages.length <= 1) {
      // don't display pager if there is only 1 page
      return null
    }

    return (
      <ul className="pagination">
        {
          pager.pages.map((page, index) =>
            <li key={index} className={pager.currentPage === page ? 'active' : ''} onClick={() => this.setPage(page)}>
              <a>{ page }</a>
            </li>
          )
        }
      </ul>
    )
  }
}

class Demo extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: ''
    }
  }
  
  componentDidMount() {
    const url = 'https://my.api.mockaroo.com/users.json?key=1e89b1d0'
    fetch(url)
      .then(resp => resp.json())
      .then(data => {
        this.setState({ data })
      })
      .catch(error => {
        console.log("Error:", error.message)
      });
  }

  render() {
    const data = this.state.data || [
      {
        id: 1,
        first_name: "Jo",
        last_name: "Pennell",
        email: "jpennell0@epa.gov",
        gender: "Female"
      },
      {
        id: 2,
        first_name: "Kellby",
        last_name: "Huggins",
        email: "khuggins1@examiner.com",
        gender: "Female"
      },
      {
        id: 3,
        first_name: "Jerome",
        last_name: "Wycliffe",
        email: "jwycliffe2@businessinsider.com",
        gender: "Female"
      },
      {
        id: 4,
        first_name: "Dmitri",
        last_name: "Friman",
        email: "dfriman3@histats.com",
        gender: "Male"
      },
      {
        id: 5,
        first_name: "Jo",
        last_name: "Pennell",
        email: "jpennell0@epa.gov",
        gender: "Female"
      },
      {
        id: 6,
        first_name: "Kellby",
        last_name: "Huggins",
        email: "khuggins1@examiner.com",
        gender: "Female"
      },
      {
        id: 7,
        first_name: "Jerome",
        last_name: "Wycliffe",
        email: "jwycliffe2@businessinsider.com",
        gender: "Female"
      },
      {
        id: 8,
        first_name: "Dmitri",
        last_name: "Friman",
        email: "dfriman3@histats.com",
        gender: "Male"
      }
    ]
    const details = [
      { name: 'id', display: 'ID' },
      { name: 'first_name', display: 'First Name' },
      { name: 'last_name', display: 'Last Name' },
      { name: 'email', display: 'Email' },
      { name: 'gender', display: 'Gender' }
    ]
    
    if (!data) {
      return (
        <main className="mdl-cell mdl-cell--8-col mdl-cell--2-offset">
          <div className="mdl-table-search mdl-cell mdl-cell--12-col mdl-grid mdl-grid--no-spacing">
            <span>Loading...</span>
          </div>
        </main>
      )
    } 
    return (
      <SearchTable
        details={details}
        data={data}
      />
    )
  }
}

ReactDOM.render(<Demo />, document.getElementById('app'))

              
            
!
999px

Console