Adding horizontal scrollbar to mui-datatable - reactjs

I'm using mui-datatable in my react app and I want to add a horizontal scrollbar to my table to display overflow columns instead of having the table stretch past the windows screen width.
Here is my code
const TableSection = (props) => {
const columns = [
{ name: "invoice_id", label: "Invoice No" },
{ name: "mode", label: "Mode" },
{ name: "date", label: "Date" },
{ name: "quantity", label: "Quantity" },
{ name: "status", label: "Status" },
{ name: "shipping_address_owner", label: "Customer" },
{
name: "product",
label: "Products",
options: {
customBodyRender: (value, tableMeta, updateValue) => (
<div>{value.join(",")}</div>
),
},
},
{
name: "payment_made",
label: "Amount paid",
options: {
customBodyRender: function (value, tableMeta, updateValue) {
return new Intl.NumberFormat().format(value); // comma separator
},
},
},
];
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>
<MUIDataTable
title={"Recent Purchases Invoice"}
data={invoiceData}
columns={columns}
options={options}
/>
</Paper>
</Grid>
</Grid>
</div>
);
};
export default TableSection;
const options = {
filterType: "checkbox",
rowsPerPage: 5,
rowsPerPageOptions: [5, 10, 15, 20],
downloadOptions: { filename: "InvoiceData.csv", separator: "," },
elevation: 6,
};
EDIT: Added table options values

createMuiTheme({
overrides: {
MUIDataTable: {
responsiveStacked: {
maxHeight: 'none',
overflowX:'auto'
},
},
},
});
In the options object you can pass responsive property. It has 3 different values...vertical, standard and simple. Stacked is from the previous version which will be deprecated soon.

You can use responsive: 'scrollMaxHeight' in options to show horizontal scroll.
const options = {
filterType: 'dropdown',
responsive: 'scrollMaxHeight',
count: total,
page: page,
rowsPerPage: tableState.rowsPerPage,
rowsPerPageOptions: [10, 20, 50, 100],
};
and then you pass options to MUIDataTable as below:
<MUIDataTable
title={"Service Request List"}
data={requests}
columns={columns}
options={options}
/>

Related

How to show dropdown options in fluent UI breadcrumbs

i wanted to show dropdown in fluent ui breadcrumbs help on building the code. please refer below image
Reference image copied from azure devops
To show the dropdown menu at breadcrumbs, you need CommandBarButton as the trigger of the dropdown and menuProps that contain the menu's item objects and pass the CommandBarButton at Breadcrumb's last item onRenderContent event handler.
Don't forget to memoize both breadcrumb's items and dropdown menuProps.
import { CommandBarButton } from "#fluentui/react/lib/Button";
...
const menuProps: IContextualMenuProps = React.useMemo(() => {
return {
items: [
{
key: "def",
text: "Dev",
onClick: () => setEnvironment("Dev"),
onRenderContent: () => {
return <MenuItem label="Dev" environment={environment} />;
}
},
...
]
};
}, [environment, setEnvironment]);
const items: IBreadcrumbItem[] = React.useMemo(() => {
return [
{ text: "Files", key: "Files", onClick: _onBreadcrumbItemClicked },
{ text: "Folder 1", key: "f1", onClick: _onBreadcrumbItemClicked },
...
{ text: "Folder 6", key: "f6", onClick: _onBreadcrumbItemClicked },
{
text: "Folder 11",
key: "f11",
onClick: _onBreadcrumbItemClicked,
isCurrentItem: true,
onRenderContent: () => {
return (
<CommandBarButton
style={{
fontSize: 18,
fontWeight: "bold",
height: "30px",
padding: 0,
background: "transparent"
}}
text={environment}
iconProps={null}
disabled={false}
checked={false}
menuProps={menuProps}
/>
);
}
}
];
}, [environment, menuProps]);
This is the complete code:

Filter/update already rendered chart.js in react.js

I'm new here, because I have decided to dive into programming, so I can fill free time between treatments in the hospital. I'm absolutely new in the programming field with no previous coding background.
The summary:
I am working on a simple page, where I fetch data from a Postgre database that is visualized using chart.js. The page is a built-in cube.js playground, using a Reactjs template. Currently, I can display various charts depending on my criteria. Like display monthly sales of a certain product in Australia. Or, I can display a second chart with daily sales in the countries I choose. Or ignore all sales that were in a certain currency. Right now, every new criterion means I have to use cube.js playground and generate a new chart on the page.
What I would like to achieve is to be able to filter already rendered charts (by a dropdown button outside the chart or inside the chart, it doesn't matter too much) and having the chart updated. Something like the pictures here, where the OP can filter charts based on the date, factory, etc.
I've tried Chart.js Example with Dynamic Dataset, chart.js tutorial on
Updating Charts and various others. But I can't seem to be able to implement any of those solutions in my code.
Here is my current code:
ChartRenderer.js
import React from "react";
import PropTypes from "prop-types";
import { useCubeQuery } from "#cubejs-client/react";
import Row from "react-bootstrap/Row";
import Spin from "react-bootstrap/Spinner";
import Col from "react-bootstrap/Col";
import { Statistic, Table } from "antd";
import { Line, Bar, Pie } from "react-chartjs-2";
const COLORS_SERIES = [
"#931F1D",
"#141446",
"#7A77FF",
];
const commonOptions = {
maintainAspectRatio: true,
};
const TypeToChartComponent = {
line: ({ resultSet }) => {
const data = {
labels: resultSet.categories().map((c) => c.category),
datasets: resultSet.series().map((s, index) => ({
label: s.title,
data: s.series.map((r) => r.value),
borderColor: COLORS_SERIES[index],
backgroundColor: COLORS_SERIES[index],
fill: false,
tension: 0.4,
})),
};
const options = { ...commonOptions };
return <Line data={data} options={options} />;
},
bar: ({ resultSet }) => {
const data = {
labels: resultSet.categories().map((c) => c.category),
datasets: resultSet.series().map((s, index) => ({
label: s.title,
data: s.series.map((r) => r.value),
backgroundColor: COLORS_SERIES[index],
fill: false,
})),
};
const options = {
...commonOptions,
scales: {
xAxes: [
{
stacked: true,
},
],
},
};
return <Bar data={data} options={options} />;
},
area: ({ resultSet }) => {
const data = {
labels: resultSet.categories().map((c) => c.category),
datasets: resultSet.series().map((s, index) => ({
label: s.title,
data: s.series.map((r) => r.value),
backgroundColor: COLORS_SERIES[index],
fill: true,
})),
};
const options = {
...commonOptions,
scales: {
yAxes: [
{
stacked: true,
},
],
},
};
return <Line data={data} options={options} />;
},
pie: ({ resultSet }) => {
const data = {
labels: resultSet.categories().map((c) => c.category),
datasets: resultSet.series().map((s) => ({
label: s.title,
data: s.series.map((r) => r.value),
backgroundColor: COLORS_SERIES,
hoverBackgroundColor: COLORS_SERIES,
borderColor: COLORS_SERIES,
hoverBorderColor: "white",
hoverOffset: 10,
})),
};
const options = { ...commonOptions };
return <Pie data={data} options={options} />;
},
number: ({ resultSet }) => {
return (
<Row
type="flex"
justify="space-around"
align="middle"
style={{ height: "100%" }}
>
<Col align="left">
{resultSet.seriesNames().map((s) => (
<Statistic value={resultSet.totalRow()[s.key]} />
))}
</Col>
</Row>
);
},
table: ({ resultSet, pivotConfig }) => {
return (
<Table
pagination={false}
columns={resultSet.tableColumns(pivotConfig)}
dataSource={resultSet.tablePivot(pivotConfig)}
/>
);
},
};
const TypeToMemoChartComponent = Object.keys(TypeToChartComponent)
.map((key) => ({
[key]: React.memo(TypeToChartComponent[key]),
}))
.reduce((a, b) => ({ ...a, ...b }));
const renderChart =
(Component) =>
({ resultSet, error }) =>
(resultSet && <Component resultSet={resultSet} />) ||
(error && error.toString()) || <Spin animation="grow text-primary" />;
const ChartRenderer = ({ vizState }) => {
const { query, chartType } = vizState;
const component = TypeToMemoChartComponent[chartType];
const renderProps = useCubeQuery(query);
return component && renderChart(component)(renderProps);
};
ChartRenderer.propTypes = {
vizState: PropTypes.object,
cubejsApi: PropTypes.object,
};
ChartRenderer.defaultProps = {
vizState: {},
cubejsApi: null,
};
export default ChartRenderer;
DashBoardPage.js
import React from "react";
import Col from "react-bootstrap/Col";
import DateRangePicker from 'react-bootstrap-daterangepicker';
import ChartRenderer from "../components/ChartRenderer";
import Dashboard from "../components/Dashboard";
import DashboardItem from "../components/DashboardItem";
const DashboardItems = [
{
id: 0,
name: "Sold by customers today",
vizState: {
query: {
measures: ["PostgreSqlTable.amount"],
timeDimensions: [
{
dimension: "PostgreSqlTable.added",
granularity: "day",
dateRange: "Today",
},
],
order: {},
dimensions: [],
filters: [
{
member: "PostgreSqlTable.operation",
operator: "contains",
values: ["Sell"],
},
],
},
chartType: "number",
},
},
{
id: 1,
name: "Bought by customers today",
vizState: {
query: {
measures: ["PostgreSqlTable.amount"],
timeDimensions: [
{
dimension: "PostgreSqlTable.added",
dateRange: "Today",
},
],
order: {},
filters: [
{
member: "PostgreSqlTable.operation",
operator: "contains",
values: ["Buy"],
},
],
},
chartType: "number",
},
},
{
id: 2,
name: "Money in the wallet",
vizState: {
query: {
measures: ["PostgreSqlTable.amount"],
timeDimensions: [
{
dimension: "PostgreSqlTable.added",
},
],
order: {
"PostgreSqlTable.amount": "desc",
},
dimensions: ["PostgreSqlTable.currency"],
filters: [
{
member: "PostgreSqlTable.currency",
operator: "equals",
values: ["EUR"],
},
],
},
chartType: "number",
},
},
{
id: 3,
name: "Monthly sales filtered by week",
vizState: {
query: {
measures: ["PostgreSqlTable.amount"],
timeDimensions: [
{
dimension: "PostgreSqlTable.added",
granularity: "week",
dateRange: "This month",
},
],
order: {
"PostgreSqlTable.amount": "desc",
},
dimensions: ["PostgreSqlTable.operation"],
filters: [
{
member: "PostgreSqlTable.operation",
operator: "notContains",
values: ["Register"],
},
],
limit: 5000,
},
chartType: "line",
},
},
{
id: 4,
name: "Countries with most customers",
vizState: {
query: {
measures: ["PostgreSqlTable.count"],
timeDimensions: [
{
dimension: "PostgreSqlTable.added",
},
],
order: {
"PostgreSqlTable.count": "desc",
},
dimensions: ["PostgreSqlTable.country"],
limit: 5,
},
chartType: "pie",
},
},
];
const DashboardPage = () => {
const dashboardItem = (item) => (
<Col className="col-4">
<DashboardItem title={item.name}>
<ChartRenderer vizState={item.vizState} />
</DashboardItem>
</Col>
);
const Empty = () => (
<div
style={{
textAlign: "center",
padding: 12,
}}
>
<h2>
No items added
</h2>
</div>
);
return DashboardItems.length ? (
<Dashboard dashboardItems={DashboardItems}>
{DashboardItems.map(dashboardItem)}
</Dashboard>
) : (
<Empty />
);
};
export default DashboardPage;
At this moment, I have no clue how to implement the filter in react.js+chart.js. I have also tried to update the array, but no success (I followed also this tutorial)
I would be most grateful for any help.
Thank you in advance, stay healthy.
Tatsu
I'd recommend using the <QueryBuilder/> component available in the Cube.js-React integration; this component provides a similar interface as that in the Developer Playground.

React Material - MUIDataTable - how to update row data

I'm looking to implement an efficient way of updating individual row entries.
My way seems does not work. Just to add, i'm getting my data from redux state.
I was contemplating on using popup modals but i'm looking to implement a more efficient way.
// action
import { HrEmployeeData } from "../../actions/employeeHR";
const EmployeeTable = (props) => {
useEffect(() => {
props.HrEmployeeData();
}, []);
const classes = useStyles();
const columns = [
{ name: "name", label: "Name" },
{ name: "phone_no", label: "Contact" },
{ name: "email", label: "Email" },
{ name: "department", label: "Department" },
{ name: "job_title", label: "Title" },
{ name: "salary", label: "Salary" },
{ name: "date_employed", label: "Date Employed" },
{
name: "Action",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button
onClick={() =>
window.alert(`Clicked "Edit" for row ${value}`)
}
>
Edit
</button>
);
},
},
},
];
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>
<MUIDataTable
title={"Employees Records"}
data={props.employeesDetail}
columns={columns}
options={options}
/>
</Paper>
</Grid>
</Grid>
</div>
);
};
export default connect(mapStateToProps, { HrEmployeeData })(EmployeeTable);

React Material - MUIDataTable - how to add content in column header

I use in my React app:
import MUIDataTable from "mui-datatables";
I'd like to add some button to my last column header (instead of the column name):
<MUIDataTable
data={data}
columns={columns}
options={options}
>
</MUIDataTable>
where columns:
export const columns = [
{
name: "name",
label: "Nazwa",
options: {
filter: true,
sort: true,
}
},
{
name: "productNumber",
label: "Numer",
options: {
filter: true,
sort: true,
}
}, (...)
How to do that? Is it possible? I can't find anything
You can define a custom body for column. You can add a column like this:
{
name: "Age",
options: {
filter: false,
customBodyRender: (value, tableMeta, updateValue) => (
<FormControlLabel
control={<TextField value={value || ''} type='number' />}
onChange={event => updateValue(event.target.value)}
/>
)
}
}
You need to use customHeadRender
const columns = [
{
name: "id",
label: "Id",
options: {
filter: false,
}
},
{
name: "subject",
label: "Subject",
options: {
filter: true,
sort: false,
}
},
{
name: "button",
options: {
customHeadRender: ({index, ...column}) => {
return (
<Button key={index}>
Click
</Button>
)
}
}
}
];

Set pagination on MaterialTable ui https://material-table.com/#/docs/features/localization?

That is my code. I would like to set pagination to 50, 100, 250 rows per page (for example). How can I achieve that?
<MaterialTable
localization={{
pagination: {
labelDisplayedRows: '4-6 of 10',
labelRowsPerPage:'{5, 10, 25,100}'
},
}}
title="Crawler Results"
columns={[
{ title: "URL", field: "url" },
{ title: "Status", field: "status" }
]}
data={state.data}
actions={[
{
icon: 'add',
tooltip: 'Add User',
isFreeAction: true,
onClick: () => {
//show crawler table and hide formular
document.getElementById('formCrawler').style.display = "block";
document.getElementById('formSpan').style.display = "block";
document.getElementById('crawlerTableID').style.display = "none";
}
}]}
/>
As mentioned in the docs, you can override the pageSizeOptions in options with an array of page sizes.
<MaterialTable
localization={{
pagination: {
labelDisplayedRows: '4-6 of 10',
labelRowsPerPage:'{5, 10, 25,100}'
},
}}
title="Crawler Results"
columns={[
{ title: "URL", field: "url" },
{ title: "Status", field: "status" }
]}
options={{
pageSizeOptions : [50, 100, 200]
}}
data={state.data}
actions={[
{
icon: 'add',
tooltip: 'Add User',
isFreeAction: true,
onClick: () => {
//show crawler table and hide formular
document.getElementById('formCrawler').style.display = "block";
document.getElementById('formSpan').style.display = "block";
document.getElementById('crawlerTableID').style.display = "none";
}
}]}
/>
Adding labelRowsPerPage didn't do anything for me. I added the following property to the MaterialTable:
options={{
pageSizeOptions: [50, 100, 250]
}}
https://material-table.com/#/docs/all-props

Resources