SHARE
TWEET

Untitled

a guest Jan 19th, 2020 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect } from 'react';
  2. import { makeStyles } from '@material-ui/core/styles';
  3. import Table from '@material-ui/core/Table';
  4. import TableBody from '@material-ui/core/TableBody';
  5. import TableCell from '@material-ui/core/TableCell';
  6. import TablePagination from '@material-ui/core/TablePagination';
  7. import TableRow from '@material-ui/core/TableRow';
  8. import Paper from '@material-ui/core/Paper';
  9. import Checkbox from '@material-ui/core/Checkbox';
  10. import FormControlLabel from '@material-ui/core/FormControlLabel';
  11. import Switch from '@material-ui/core/Switch';
  12. import EnhancedTableToolbar from './EnhancedTableToolbar'; // Import a component from another file
  13. import EnhancedTableHead from './EnhancedTableHead'; // Import a component from another file
  14. import { get_campaigns } from './Api';
  15.  
  16. function desc(a, b, orderBy) {
  17.   if (b[orderBy] < a[orderBy]) {
  18.     return -1;
  19.   }
  20.   if (b[orderBy] > a[orderBy]) {
  21.     return 1;
  22.   }
  23.   return 0;
  24. }
  25.  
  26. export function stableSort(array, cmp) {
  27.   const stabilizedThis = array.map((el, index) => [el, index]);
  28.   stabilizedThis.sort((a, b) => {
  29.     const order = cmp(a[0], b[0]);
  30.     if (order !== 0) return order;
  31.     return a[1] - b[1];
  32.   });
  33.   return stabilizedThis.map(el => el[0]);
  34. }
  35.  
  36. export function getSorting(order, orderBy) {
  37.   return order === "desc"
  38.     ? (a, b) => desc(a, b, orderBy)
  39.     : (a, b) => -desc(a, b, orderBy);
  40. }
  41.  
  42. function searchByName(array, searchTerm) {
  43.   return array.filter(item => {
  44.     if (
  45.       item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
  46.       item.updated_at.toLowerCase().includes(searchTerm.toLowerCase())
  47.     ) {
  48.       return item;
  49.     }
  50.     return null;
  51.   });
  52. }
  53.  
  54. export const useStyles = makeStyles(theme => ({
  55.   root: {
  56.     display: 'flex',
  57.     flexDirection: 'column',
  58.     alignItems: 'center',
  59.   },
  60.   paper: {
  61.     marginBottom: theme.spacing(2),
  62.     width: '100%',
  63.     boxShadow: 'none',
  64.     padding: 0,
  65.   },
  66.   table: {
  67.     width: '100%',
  68.   },
  69.   tableWrapper: {
  70.     overflowX: 'auto',
  71.   },
  72.   visuallyHidden: {
  73.     border: 0,
  74.     clip: 'rect(0 0 0 0)',
  75.     height: 1,
  76.     margin: -1,
  77.     overflow: 'hidden',
  78.     padding: 0,
  79.     position: 'absolute',
  80.     top: 20,
  81.     width: 1,
  82.   },
  83.   button: {
  84.     margin: theme.spacing(1),
  85.   },
  86. }));
  87.  
  88. export default function DataTable() {
  89.   const classes = useStyles();
  90.   const [order, setOrder] = useState('asc');
  91.   const [orderBy, setOrderBy] = useState('campaign_id');
  92.   const [selected, setSelected] = useState([]);
  93.   const [page, setPage] = useState(0);
  94.   const [dense, setDense] = useState(false);
  95.   const [rowsPerPage, setRowsPerPage] = useState(5);
  96.   const [campaigns, setCampaigns] = useState([]);
  97.   const [allCampaigns, setAllCampaigns] = useState([]);
  98.   const [isSearch, setIsSearch] = useState(false);
  99.   const [searchTerm, setSearchTerm] = useState('');
  100.  
  101.   useEffect(() => {
  102.     async function getData() {
  103.       try {
  104.         const res = await get_campaigns();
  105.         const allCampaigns = res.campaigns;
  106.         setCampaigns(allCampaigns);
  107.         setAllCampaigns(allCampaigns);
  108.       } catch (err) {
  109.         console.log('getting data error:', err);
  110.       }
  111.     }
  112.     getData();
  113.   },[]);
  114.  
  115.   const onSearch = term => {
  116.     setSearchTerm(term);
  117.     setCampaigns(searchByName(allCampaigns, term));
  118.   };
  119.  
  120.   const handleRequestSort = (event, property) => {
  121.     const isDesc = orderBy === property && order === 'desc';
  122.     setOrder(isDesc ? 'asc' : 'desc');
  123.     setOrderBy(property);
  124.   };
  125.  
  126.   const handleSelectAllClick = event => {
  127.     if (event.target.checked) {
  128.       const newSelecteds = campaigns.map(n => n.campaign_id);
  129.       setSelected(newSelecteds);
  130.       return;
  131.     }
  132.     setSelected([]);
  133.   };
  134.  
  135.   const handleClick = (event, campaign_id) => {
  136.     const selectedIndex = selected.indexOf(campaign_id);
  137.     let newSelected = [];
  138.  
  139.     if (selectedIndex === -1) {
  140.       newSelected = newSelected.concat(selected, campaign_id);
  141.     } else if (selectedIndex === 0) {
  142.       newSelected = newSelected.concat(selected.slice(1));
  143.     } else if (selectedIndex === selected.length - 1) {
  144.       newSelected = newSelected.concat(selected.slice(0, -1));
  145.     } else if (selectedIndex > 0) {
  146.       newSelected = newSelected.concat(
  147.         selected.slice(0, selectedIndex),
  148.         selected.slice(selectedIndex + 1)
  149.       );
  150.     }
  151.  
  152.     setSelected(newSelected);
  153.   };
  154.  
  155.   const handleChangePage = (event, newPage) => {
  156.     setPage(newPage);
  157.   };
  158.  
  159.   const handleChangeRowsPerPage = event => {
  160.     setRowsPerPage(parseInt(event.target.value, 10));
  161.     setPage(0);
  162.   };
  163.  
  164.   const handleChangeDense = event => {
  165.     setDense(event.target.checked);
  166.   };
  167.  
  168.   const isSelected = campaign_id => selected.indexOf(campaign_id) !== -1;
  169.  
  170.   const emptyRows = rowsPerPage - Math.min(rowsPerPage, campaigns.length - page * rowsPerPage);
  171.   return (
  172.     <div className={classes.root}>
  173.       <Paper className={classes.paper}>
  174.         <EnhancedTableToolbar
  175.           numSelected={selected.length}
  176.           isSearch={isSearch}
  177.           setIsSearch={setIsSearch}
  178.           searchTerm={searchTerm}
  179.           onSearch={onSearch}
  180.           numCampaigns={campaigns.length}
  181.         />
  182.         <div className={classes.tableWrapper}>
  183.           <Table
  184.             className={classes.table}
  185.             aria-labelledby="tableTitle"
  186.             size={dense ? 'small' : 'medium'}
  187.             aria-label="enhanced table"
  188.           >
  189.             <EnhancedTableHead
  190.               classes={classes}
  191.               numSelected={selected.length}
  192.               order={order}
  193.               orderBy={orderBy}
  194.               onSelectAllClick={handleSelectAllClick}
  195.               onRequestSort={handleRequestSort}
  196.               rowCount={campaigns.length}
  197.             />
  198.             <TableBody>
  199.               {stableSort(campaigns, getSorting(order, orderBy))
  200.                 .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
  201.                 .map((campaign, index) => {
  202.                   const isItemSelected = isSelected(campaign.campaign_id);
  203.                   const labelId = `enhanced-table-checkbox-${index}`;
  204.  
  205.                   return (
  206.                     <TableRow
  207.                       hover
  208.                       onClick={event => handleClick(event, campaign.campaign_id)}
  209.                       role="checkbox"
  210.                       aria-checked={isItemSelected}
  211.                       tabIndex={-1}
  212.                       key={campaign.campaign_id}
  213.                       selected={isItemSelected}
  214.                     >
  215.                       <TableCell padding="checkbox">
  216.                         <Checkbox
  217.                           checked={isItemSelected}
  218.                           inputProps={{ 'aria-labelledby': labelId }}
  219.                         />
  220.                       </TableCell>
  221.                       <TableCell align="left">{campaign.name}</TableCell>
  222.                       <TableCell align="left">{campaign.updated_at}</TableCell>
  223.                     </TableRow>
  224.                   );
  225.                 })}
  226.               {emptyRows > 0 && (
  227.                 <TableRow style={{ height: (dense ? 33 : 53) * emptyRows }}>
  228.                   <TableCell colSpan={6} />
  229.                 </TableRow>
  230.               )}
  231.             </TableBody>
  232.           </Table>
  233.         </div>
  234.         <TablePagination
  235.           rowsPerPageOptions={[5, 10, 25]}
  236.           component="div"
  237.           count={campaigns.length}
  238.           rowsPerPage={rowsPerPage}
  239.           page={page}
  240.           backIconButtonProps={{
  241.             'aria-label': 'previous page',
  242.           }}
  243.           nextIconButtonProps={{
  244.             'aria-label': 'next page',
  245.           }}
  246.           onChangePage={handleChangePage}
  247.           onChangeRowsPerPage={handleChangeRowsPerPage}
  248.         />
  249.       </Paper>
  250.       <FormControlLabel
  251.         control={<Switch checked={dense} onChange={handleChangeDense} />}
  252.         label="Dense padding"
  253.       />
  254.     </div>
  255.   );
  256. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top