Material-UI datagrid datepicker - javascript

I'm making a scheduler using Material-UI's DataGrid component and it looks great so far. Here's how I have it set up:
import React, {useState, useEffect } from "react";
import {DataGrid, GridToolbar} from '#material-ui/data-grid';
import axios from 'axios'
const columns = [
{
field: 'name',
headerName: 'Name',
editable: true,
flex: 1
},
{
field: 'email',
headerName: 'Email',
editable: true,
flex: 1
},
{
field: 'number',
headerName: 'Phone Number',
editable: true,
flex: 1
},
{
field: 'appointmentType',
headerName: 'Appointment Type',
editable: true,
flex: 1
},
{
field: 'description',
headerName: 'Description',
editable: true,
flex: 1
},
{
field: 'date',
headerName: 'Date',
editable: true,
width: 150,
type: 'dateTime'
},
];
const Scheduler = () => {
const [tableData, setTableData] = useState([]);
useEffect(() => {
fetchData()
}, [])
const fetchData = async () => {
const {data} = await axios.get("/api/patients")
setTableData(data.data)
console.log(data)
}
return (
<div style={{display: 'flex', flexDirection: 'column', paddingTop: 100}}>
<div style={{textAlign: 'center', paddingBottom: 30}}>
<h1>Appointments</h1>
</div>
<div style={{display:'flex', justifyContent: 'center', alignItems:'center'}}>
<div style={{height: 400, width: '90%'}}>
<DataGrid
getRowId={(row) => row._id}
rows={tableData}
columns={columns}
pageSize={10}
rowsPerPageOptions={[10]}
autoHeight
components={{
Toolbar: GridToolbar
}}
/>
</div>
</div>
</div>
);
};
export default Scheduler;
I have a couple questions.
How do I make the datetime picker built into the datagrid (when type: is declared as 'datetime') localized? This system is being designed for something outside the US, so I'd like to localize it to British English.
How would I restrict certain dates and times in the aforementioned datetime picker?
Thank you.

Related

Unable to update state from onClick event of MDBDatable row in React

I'm using MDBReact for the creation of a simple data table that has some rows and setMe and getMe buttons. onClick of setMe button I wish to set a value to the cropName state value and onClick of getMe button, I wish to retrieve the update state value.
The problem is that I only receive emptystring values every time inside the getMe function even after updating the state.
I have tried the following code, but unfortunately, it does not seem to update the state value. I only get an emptystring when the getMe button is clicked.
import React, { useState } from 'react';
import { render } from 'react-dom';
import { MDBDataTable } from 'mdbreact';
import './style.css';
import '#fortawesome/fontawesome-free/css/all.min.css';
import 'bootstrap-css-only/css/bootstrap.min.css';
import 'mdbreact/dist/css/mdb.css';
function App() {
const [cropName, setCropName] = useState('');
const [data, setData] = useState([]);
function setMe(e) {
console.log(setCropName('Hello'));
}
function getMe(e) {
console.log(cropName);
}
function loadTable() {
setData({
columns: [
{
label: 'Action',
field: 'radio',
sort: 'asc',
width: 150,
},
{
label: 'Position',
field: 'position',
sort: 'asc',
width: 270,
},
{
label: 'Office',
field: 'office',
sort: 'asc',
width: 200,
},
{
label: 'Age',
field: 'age',
sort: 'asc',
width: 100,
},
{
label: 'Start date',
field: 'date',
sort: 'asc',
width: 150,
},
{
label: 'Salary',
field: 'salary',
sort: 'asc',
width: 100,
},
],
rows: [
{
radio: (
<div className="field-input pt-2">
Click this
<button id="asdfsdasafsdf" onClick={setMe}>
set me!
</button>
<button id="asdfsdasafsdf" onClick={getMe}>
get me!
</button>
</div>
),
position: 'System Architect',
office: 'Edinburgh',
age: '61',
date: '2011/04/25',
salary: '$320',
},
{
name: 'Garrett Winters',
position: 'Accountant',
office: 'Tokyo',
age: '63',
date: '2011/07/25',
salary: '$170',
},
],
});
}
return (
<div>
<MDBDataTable striped bordered hover data={data} />
<button onClick={loadTable}>Load Table</button>
</div>
);
}
render(<App />, document.getElementById('root'));
Here the live demo of my implementation.
It looks like the state updates are not available to the functions fired from the table row event. I got my way around it by using useEffect statement and setting the dependency as the property that gets modified by the table row event.
import React, { useState, useEffect } from 'react';
import { render } from 'react-dom';
import { MDBDataTable } from 'mdbreact';
import './style.css';
import '#fortawesome/fontawesome-free/css/all.min.css';
import 'bootstrap-css-only/css/bootstrap.min.css';
import 'mdbreact/dist/css/mdb.css';
function App() {
const [cropName, setCropName] = useState('');
const [data, setData] = useState([]);
useEffect(()=>{
console.log('Crop changed')
}, [cropName])
function setMe(e) {
setCropName('Hello ID: '+Math.random());
}
function getMe(e) {
console.log(cropName);
}
function loadTable() {
setData({
columns: [
{
label: 'Action',
field: 'radio',
sort: 'asc',
width: 150,
},
{
label: 'Position',
field: 'position',
sort: 'asc',
width: 270,
},
{
label: 'Office',
field: 'office',
sort: 'asc',
width: 200,
},
{
label: 'Age',
field: 'age',
sort: 'asc',
width: 100,
},
{
label: 'Start date',
field: 'date',
sort: 'asc',
width: 150,
},
{
label: 'Salary',
field: 'salary',
sort: 'asc',
width: 100,
},
],
rows: [
{
radio: (
<div className="field-input pt-2">
Click this
<button id="asdfsdasafsdf" onClick={setMe}>
set me!
</button>
<button id="asdfsdasafsdf" onClick={getMe}>
get me!
</button>
</div>
),
position: 'System Architect',
office: 'Edinburgh',
age: '61',
date: '2011/04/25',
salary: '$320',
},
{
name: 'Garrett Winters',
position: 'Accountant',
office: 'Tokyo',
age: '63',
date: '2011/07/25',
salary: '$170',
},
],
});
}
return (
<div>
<MDBDataTable striped bordered hover data={data} />
<button onClick={loadTable}>Load Table</button>
{cropName}
</div>
);
}
render(<App />, document.getElementById('root'));
Demo

React Data Table Component - Header row not showing full text

so I am using an npm package called react-data-table-component. A problem that I am having with this is that I can't adjust the width enough to display the full header text, as you can see here:
Here is the custom styling that I am using with this data table:
const CustomStyle = {
noData: {
style: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'white',
},
},
rows: {
style: {
zIndex: 2,
minHeight: '30px !important', // override the row height
fontSize: '14px',
whiteSpace: 'pre',
},
},
table: {
style: {
zIndex: 1,
},
},
headRow: {
style: {
minHeight: '40px',
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderBottomWidth: '2px',
},
},
headCells: {
style: {
fontSize: '16px',
justifyContent: 'left',
wordWrap: 'breakWord',
},
},
subHeader: {
style: {
minHeight: '40px',
},
},
pagination: {
style: {
minHeight: '40px',
},
pageButtonsStyle: {
borderRadius: '50%',
height: '40px',
width: '40px',
padding: '8px',
margin: 'px',
cursor: 'pointer',
},
},
};
Here is the width setting that I am using for each column:
const columns = [
{
name: 'Action',
selector: row => row['CASE_ID'],
width: '6%',
maxWidth: 'auto',
cell: row => {
return (
<div>
<Row>
<Col className="ml-3">
<Link to={{ pathname: "/wlmonitoring/user-case-wl", caseID: row.CASE_ID, cifID: row.NO_CIF }}>
<img alt="" src={editIcon} className="edit-icon" />
</Link>
</Col>
</Row>
</div>
);
},
},
{
name: 'Case ID',
selector: row => row['CASE_ID'],
width: '7%',
maxWidth: 'auto',
cell: row => {
return (
"WMC" + row.CASE_ID
)
}
},
{
name: 'Created Date',
selector: row => row['AUDIT_DATE_CREATED'],
width: '10%',
maxWidth: 'auto',
sortable: true,
cell: row => {
return (
moment(row.AUDIT_DATE_CREATED).format(dateFormat)
)
}
},
Currently I am using percentage to define the width, but I tried setting the exact width in pixel, but that would cause the last header to protrude out of the table like so:
If anyone can help me figure out what the exact issue is I would really appreciate it.
The accepted answer didn't work for me. What did was placing the title inside a div, that way the component will not try to shorten in.
Eg from:
{
name: 'Case ID',
...
}
To:
{
name: <div>Case ID</div>,
...
}
Just add this style to your App.css or App.scss and do hard refresh ctrl+shift+R
.lnndaO {
white-space: pre-line !important;
}

MUI DataGrid layout issues using React

Been trying to get MUI DataGrid to work for a few hours now, but for some reason the styling is placing the pagination information at the top of the table, on top of the column headers.
Maybe its something stupid I'm doing. I have tried a really simple version to illustrate my issues. Hope someone can please help me. BTW I use v5+ of MUI and DataGrid. React is v17+
import React, { FC } from "react";
import { DataGrid, GridRowModel } from "#mui/x-data-grid";
import { GridColDef } from "#mui/x-data-grid";
export const DataGridTest: FC = () => {
const paginationSize = 20;
const columns: GridColDef[] = [
{ field: "username", headerName: "Username", flex: 1, sortable: false, filterable: false },
{ field: "first_name", headerName: "First Name", flex: 1, sortable: false, filterable: false },
{ field: "last_name", headerName: "Last Name", flex: 1, sortable: false, filterable: false },
{ field: "email", headerName: "Email", flex: 1, sortable: false, filterable: false },
{ field: "phone", headerName: "Phone", flex: 1, sortable: false, filterable: false },
];
const rows: GridRowModel[] = [
{
id: 1,
username: "Tony",
first_name: "Tony",
last_name: "Ballony",
email: "Tony#test.com",
phone: "0754512222",
},
{
id: 2,
username: "Joe",
first_name: "Joeseph",
last_name: "Willson",
email: "joe#test.com",
phone: "0754512333",
},
];
return (
<div>
<DataGrid rows={rows} columns={columns} pageSize={paginationSize} />
</div>
);
};
The output looks like this.
So you can see that the pagination section that should be shown below the table data is instead positioned at the top of the page. In fact the border that should be around the data is also moved to the top. I hope someone can help me out here.
You have to specify the height of DataGrid, like:
//// Your code ////
return (
<div>
<DataGrid
style={{ height: "700px" }}
rows={rows}
columns={columns}
pageSize={paginationSize} />
</div>
);
};
You can use stylesheets instead of inline styles ofc. It's just an example.

How can i delete items from FlatList one by one by clicking via state

I've created a simple list into a FlatList, Items have been gotten from an array named data. I want to remove items one by one by clicking on each item but my problem is that when i click on a item all of them get deleted simultaneously.
How can i fix this?
This is the what look like my app:
And this is the code:
const FoodList = () => {
const data = [
{ text: 'test1', backgroundColor: 'teal' },
{ text: 'test2', backgroundColor: 'teal' },
{ text: 'test3', backgroundColor: 'teal' },
{ text: 'test4', backgroundColor: 'teal' },
{ text: 'test5', backgroundColor: 'teal' },
{ text: 'test6', backgroundColor: 'teal' },
{ text: 'test7', backgroundColor: 'teal' },
{ text: 'test8', backgroundColor: 'teal' },
{ text: 'test9', backgroundColor: 'teal' },
{ text: 'test10', backgroundColor: 'teal' },
{ text: 'test11', backgroundColor: 'teal' },
]
let [itemState, setitemState] = useState(data);
return (
<View style={styles.container}>
<FlatList
data={itemState}
keyExtractor={(item, index) => index}
renderItem={({ item, index }) => (
<TouchableOpacity
style={[
{ flexDirection: 'row' }, { width: '100%' }, { alignItems: 'center' }, { flex: 1 }, { justifyContent: 'space-between' },
{ backgroundColor: item.backgroundColor }, { marginBottom: 10 }
]}
activeOpacity={0.7}
onPress={() => {
let removeItem = itemState.map((_item, _Index) => _Index !== index);
setitemState(itemState = removeItem);
}}
>
<Text style={{ fontSize: 30, color: 'white' }} >{item.text}{item.name}</Text>
<Icon type='FontAwesome5' name='trash-alt' style={{ color: 'white' }} />
</TouchableOpacity>
)}
/>
</View>
)
}
The problem lies on the function you used to remove item.
The map() method creates a new array with the results of calling a
function for every array element.
The filter() method creates an array filled with all array elements
that pass a test.
so when you run map((_item, _Index) => _Index !== index) your removeItem will be:
[false, false, false, true, false, false, false, false, false, false, false]
bunch of booleans doesn't get rendered obviously :)
in order to to remove the item use filter((_item, _Index) => _Index !== index)
Try doing this instead
onPress={() => {
setitemState(prevItemState => prevItemState.filter((_item, _Index) => _Index !== index));
}}

Creating a React Table with functional Components in React.js

I'm new to this coding world and trying to learn Javascript and its frameworks. I'm trying to create a React table with functional components. I am able to create the table fine but the data is not rendering, tried using the fetch hook method. Can anyone help me out with something else ? Here is the code:
import React, { useState, useEffect } from "react";
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import '../components/mystyle.css'
const FunctionalComponent = () => {
const [employees, setEmployees] = useState({});
const [isError, setErrors] = useState(false)
useEffect(() => {
async function fetchData() {
const res = await fetch("http://localhost:7000/employees");
res
.json()
.then(res => setEmployees({employeeDetails: res}))
.catch(err => setErrors(err));
}
fetchData();
}, []);
useEffect(() => {
async function fetchData() {
const resctc = await fetch("http://localhost:7000/employee/ctc");
resctc
.json()
.then(resctc => setEmployees({totalCtc: resctc}))
.catch(err => setErrors(err));
}
fetchData();
}, []);
const columns = [
{
Header: "EmployeeID",
accessor: "EmployeeId",
style: {
textAlign: 'center',
}
},
{
Header: "Name",
accessor: "name",
style: {
textAlign: 'center'
}
},
{
Header: "Project",
accessor: "Project",
style: {
textAlign: 'center'
}
},
{
Header: "Experience",
accessor: "experience",
style: {
textAlign: 'center'
}
},
{
Header: "Salary",
accessor: "salary",
style: {
textAlign: 'center'
}
},
{
Header: "DateofJoining",
accessor: "DOJ",
style: {
textAlign: 'center'
}
},
{
Header: "Blood Group",
accessor: "Blood group",
style: {
textAlign: 'center'
}
},
{
Header: "Actions",
Cell: props => {
return (
<button style={
{
backgroundColor: 'white',
color: "red",
textAlign: 'center'
}
}
>
View
</button>
)
},
width: 100,
maxWidth: 100,
minWidth: 100,
}
]
return (
<div>
<div style={{ display: 'flex',
justifyContent: "space-between",
maxWidth: '100',
maxHeight: '100',
padding: '20px',
backgroundColor: '#fefefe'
}}>
<img src={Logo} alt={Logo} maxWidth='30px' />
</div>
<div class="container-fluid" >
<div style={
{
display: 'flex',
justifyContent: "space-between",
margin: '10px'
}
}>
<div style={
{
maxWidth: '100',
fontSize: '2vw',
color: 'red'
}
}>Employee List</div>
<div style={
{
background: 'linear-gradient(to right, #f0f0f0 50%, blue 50%)',
textAlign: 'center',
maxWidth: '100',
border: '1px solid blue',
borderRadius: '35px',
padding: '10px',
}
}>
<span style={
{
color: 'blue',
fontSize: '16px',
padding: '5px 24px',
borderRadius: '35px'
}
}
>Total CTC</span>
<span style={
{ color: 'white', fontSize: '16px', padding: '5px 24px', borderRadius: '35px' }
}
>{employees.totalCtc}/-</span>
</div>
</div>
<ReactTable columns={columns} data={employees.employeeDetails} defaultPageSize={10}></ReactTable>
</div>
<div>
<span>{JSON.stringify(employees)}</span>
<hr />
<span>Is Error: {JSON.stringify(isError)}</span>
</div>
</div>
)
}
export default FunctionalComponent;

Categories