Javascript sort table inside map - javascript

I would like to sort some data that I am sending via "tableCells" object, using props.
const tableColumns = [
'Número do Bloco',
'Andar do apartamento',
'Número do apartamento',
'Tamanho do apartamento',
'Número da vaga',
'Ações',
];
Getting all the cells information via map, as follow.
How could I sort each column triggered by user click?
<TableRow>
{props.tableCells
? props.tableCells.map((tableCellContent) => (
<TableCell
align='center'
className={classes.tableCellAdjustment}
>
{document[tableCellContent]}
</TableCell>
))
: ''}
<TableCell
align='center'
className={classes.tableCellAdjustment}
>
<Fab
color='default'
aria-label='edit'
size='small'
className={classes.marginAdjustment}
>
<EditIcon />
</Fab>
<Fab
color='default'
aria-label='delete'
size='small'
className={classes.marginAdjustment}
>
<DeleteIcon
//onClick={() => this.props.deleteLine(document)}
/>
</Fab>
</TableCell>
</TableRow>

Related

How to use group table material ui in reactjs?

I use table material UI and
useEffect(() => {
if (props.grouping){
const { groupProperty, rows } = props;
const groups = props.rows.reduce((acc, row) => {
acc[row[groupProperty]] = acc[row[groupProperty]] || [];
acc[row[groupProperty]].push(row);\
return acc;
}, {});
setGroups(groups)
const keys = Object.keys(groups);
setDataGroup(keys)
}
}, [props.rows,props.schema]);
<TableBody>
<>
{props.grouping && (
dataGroup.map(key => (
<TableRow className={clsx(classes.row, props.rowClassName)}>
<TableCell colspan="5">
<CardActions disableActionSpacing>
<b>
{key}
</b>
<IconButton
className={expanded[key] ? classes.expandOpen : classes.expand}
onClick={() => handleExpandClick(key)}
aria-expanded={expanded[key]}
aria-label="Show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expanded[key]} timeout="auto" unmountOnExit>
<MuiTable {...other}>
<TableBody>
{groups[key].map(row => (
<TableRow >
<TableCell >{row.wageTitle}</TableCell>
<TableCell numeric>{row.buy}</TableCell>
<TableCell numeric>{row.sell}</TableCell>
<TableCell numeric>{row.buyMaximum}</TableCell>
<TableCell numeric>{row.sellMaximum}</TableCell>
</TableRow>
)
)}
</TableBody>
</MuiTable>
</Collapse>
</TableCell>
</TableRow>
))
)}
.....
<Table grouping={true} rows={tableData} className={classes.table} schema={schema} groupProperty="deductionTypeTitle" ></Table>
I use this link How to group table in reactjs?
..But I want this grouping to be based on two data like this: https://codesandbox.io/s/l9ijbc?file=/demo.js
Someone can help me

how to bind data in material-ui using redux hooks

I am using material-UI and redux in react I am using first-time redux so I am confused about how to implement it with my list items.
here is my code of product.js and I am successfully getting data in my redux store, I will show you below
const dispatch = useDispatch();
const {loading, product, error, productCount} = useSelector(state => state.products);
console.log(loading)
console.log(product)
console.log(error)
console.log(productCount)
useEffect(()=>{
const data = dispatch(getProducts());
console.log(data)
},[dispatch])
here is my code of table
<TableContainer component={Paper}>
<Table sx={{ minWidth: 500 }} aria-label="custom pagination table">
<TableBody>
{(rowsPerPage > 0
? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: rows
).map((row) => (
<TableRow key={row.name}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell style={{ width: 160 }} align="right">
{row.calories}
</TableCell>
<TableCell style={{ width: 160 }} align="right">
{row.fat}
</TableCell>
</TableRow>
))}
{emptyRows > 0 && (
<TableRow style={{ height: 53 * emptyRows }}>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
colSpan={3}
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
SelectProps={{
inputProps: {
'aria-label': 'rows per page',
},
native: true,
}}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
ActionsComponent={TablePaginationActions}
/>
</TableRow>
</TableFooter>
</Table>
if I show to my redux data so I am receiving data on this page
here is my console image
I hope it will be enough code to describe my problem but if anyone want to see further code to understand my problem so i will provide it

React function is always called with same parameter in a loop

I have a data array and display its elements in table rows. The last table cell includes a menu item which calls a function with parameter.
The problem is that function handleOpenApproveDialog is always fired with same data element, the last element of myData array.
CodeSandbox link
const handleOpenApproveDialog = (ev, item) => {
setAnchorEl(null);
dispatch(openApproveDialog(item));
//* problem: incoming item parameter is always same. The last element of myData array.
};
<TableBody>
{myData.map((n, i) => {
return (
<TableRow
tabIndex={-1}
key={i}
onClick={(event) => handleRowClick(event, n)}
>
<TableCell className="p-4 md:p-16" component="th" scope="row">
{n.company}
</TableCell>
<TableCell
className="p-4 md:p-16"
component="th"
scope="row"
align="right"
>
<IconButton
aria-label="actions"
id="actions-button"
aria-controls={isMenuOpen ? "actions-menu" : undefined}
aria-expanded={isMenuOpen ? "true" : undefined}
aria-haspopup="true"
onClick={(ev) => {
handleMenuClick(ev);
ev.stopPropagation();
}}
>
<MoreVertIcon />
</IconButton>
<Menu
id="actions-menu"
anchorEl={anchorEl}
open={isMenuOpen}
onClose={handleMenuClose}
>
<MenuItem
onClick={(ev) => {
handleOpenApproveDialog(ev, n);
ev.stopPropagation();
}}
>
Approve
</MenuItem>
</Menu>
</TableCell>
</TableRow>
);
})}
</TableBody>

How do I map over data from API in a collapsible table?

I don't know if the question captures what I had in my but I will explain below...
I fetched data from API and mapped into a collapsible table. Full details of the data should be embedded in EACH row such that onclick on each row, reveals the full details. Here's the code below
function Encounter() {
const [open2, setOpen2] = useState(false);
const [details, setDetails] = useState([]);
const getDetails = async () => {
try {
const fetch = await Axios.get(
"https://pshs3.herokuapp.com/all/encounter"
);
setDetails(fetch.data.data)
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getDetails();
}, []);
return (
<Wrapper>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell/>
<TableCell >
Enrollment ID
</TableCell>
<TableCell >
Encounter
</TableCell>
<TableCell>
Facility Code
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{details.map((detail, idx) => {
return (
<>
<TableRow sx={{ "& > *": { borderBottom: "unset" } }}>
<TableCell>
<IconButton
aria-label="expand row"
size="small"
onClick={() => setOpen(!open)}
>
{open ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
)}
</IconButton>
</TableCell>
<TableCell key={idx}>
{detail.enrollment_id}
</TableCell>
<TableCell key={idx}>
{detail.encounter}
</TableCell>
<TableCell key={idx}>
{detail.faciity_code}
</TableCell>
</TableRow>
<TableRow>
<TableCell
style={{ paddingBottom: 0, paddingTop: 0 }}
colSpan={6}
>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box sx={{ margin: 1 }}>
<Typography variant="h6" gutterBottom component="div">
Details
</Typography>
<Tooltip />
</Box>
</Collapse>
</TableCell>
</TableRow>
</>
);
})}
</TableBody>
</Table>
</Wrapper>
);
}
export default Encounter;
The problem I have is how to implement the open and setOpen state to individual row, also the Tooltip component(which is a the full table details from the API) to display full details of each row onclick which should correspond to the selected row in question.
Here are two solutions to the first problem.
1. Create a separate component for each <TableRow />
This component will have its own state and allows you to collapse/expand each row individually.
2. Use a dictionary for the open state
Since you have multiple (dynamic) rows, you can introduce a dictionary for the open state.
const [open, setOpen] = useState({});
For each row, you will use the open[idx] property to determine if the row should be "open"
<Collapse in={open[idx]} timeout="auto" unmountOnExit>
And in the <IconButton /> component, set the state based on the current row state.
<IconButton
aria-label="expand row"
size="small"
onClick={() => setOpen(current => ({ ...current, [idx]: !current[idx] }))}
>
Firstly add a variable in your details object:
const getDetails = async () => {
try {
const fetch = await Axios.get(
"https://pshs3.herokuapp.com/all/encounter"
);
const response = fetch.data.data;
response.map((elem) => elem.open = false)
setDetails(response)
} catch (err) {
console.log(err);
}
};
Then you can change the open variable for each element in details:
<IconButton
aria-label="expand row"
size="small"
onClick={() => detail.open = !detail.open)}
>
You might need to update the state, so change your onClick:
onClick={() => changeOpenStatus(idx))}
and the function:
const changeOpenStatus = (idx) => {
const newDetails = {...details}
newDetails[idx].open = !newDetails[idx].open;
setDetails(newDetails)
}

React issue mapping payload to table with children array

I am getting a payload and trying to map the data to a table. I am having difficulty with mapping because of the auditline array.
Does anyone know of way of flattening the auditline so that I can map my data correctly.
payload:
action:
id: 301
module : 2
name: "Create folder"
auditline:
0: Id: 1723
description:"Folder has been changed from Matlab to C#"
1: Id: 1724
description:"Folder name is Matlab"
This is the map function snippet.
<TableBody>
{data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map(n => {
const isSelected = this.isSelected(n.id);
return (
<TableRow
hover
onClick={event => this.handleClick(event, n.id)}
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
>
<TableCell>{n.action.name}</TableCell>
<TableCell>{n.auditLines.description}</TableCell>
<TableCell>
</TableCell>
</TableRow>
);
})}
You could map your array of audits to create multiple table cells :
<TableRow
hover
onClick={event => this.handleClick(event, n.id)}
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
>
<TableCell>{n.action.name}</TableCell>
{n.auditLines.map(audit => <TableCell key={audit.id}>{audit.description}</TableCell>)}
<TableCell>
</TableCell>
</TableRow>
Or, if you want all of them in a single one, use join

Categories

Resources