Why does this bar chart refresh when the others do? - reactjs

I'm sorry for not being good at English.
Using the KendoUI React demo, I've encountered a weird issue with the bar charts.
I gave each chart an interval of 3, 5, or 10 seconds, intending that each one refreshes by 3 seconds, 5 seconds, and 10 seconds.
But when I turn on the dev mode and confirm it, the charts refresh together every second the other chart does.
FYI, This code is to be child components into a map of the parent component, so I cannot divide that component by each page.
I hope to get a good answer to this situation.
pages/disk-index
import { Chart, ChartTooltip, ChartSeries, ChartSeriesItem } from '#progress/kendo-react-charts';
import { useState, useEffect, useRef } from 'react';
import Disk from './disk';
export default function Home() {
const intervalDisk = useRef(null);
const diskData1 = [{ categoryField: 'root', value: 40, color: 'blue' }];
const [diskData1State, setDiskData1State] = useState(diskData1);
const isClient = typeof window === 'object';
useEffect(() => {
if (isClient) {
intervalDisk.current = setInterval(() => {
diskData1[0].value = Math.floor(Math.random() * 100);
// console.log(new Date() + ', ' + diskData1[0].value);
setDiskData1State(JSON.parse(JSON.stringify(diskData1)));
}, 10000);
return () => clearInterval(intervalDisk.current);
}
}, []);
return (
<>
<Disk diskId="1" interval="3000" />
<Disk diskId="2" interval="5000" />
<div id="diskDataId2">
<Chart
style={{
width: '90%',
height: '85%',
position: 'center center',
}}
>
<ChartTooltip />
<ChartSeries>
<ChartSeriesItem
type="bar"
stack={{
type: 'normal',
}}
gap={2}
spacing={0.35}
categoryField="categoryField"
colorField="color"
data={diskData1}
tooltip={true}
/>
</ChartSeries>
</Chart>
</div>
</>
);
}
pages/disk
import { Chart, ChartTooltip, ChartSeries, ChartSeriesItem } from '#progress/kendo-react-charts';
import { useState, useEffect, useRef } from 'react';
export default function Disk(props) {
console.log(JSON.stringify(props));
const intervalDisk = useRef(null);
const diskData1 = [{ categoryField: 'root', value: 40, color: 'red' }];
const [diskData1State, setDiskData1State] = useState(diskData1);
useEffect(() => {
intervalDisk.current = setInterval(() => {
diskData1[0].value = Math.floor(Math.random() * 100);
// console.log(new Date() + ', ' + diskData1[0].value);
setDiskData1State(JSON.parse(JSON.stringify(diskData1)));
}, Number(props.interval));
return () => clearInterval(intervalDisk.current);
}, [diskData1State]);
return (
<>
<div id={'diskData' + props.diskId}>
<Chart
style={{
width: '90%',
height: '85%',
position: 'center center',
}}
>
<ChartTooltip />
<ChartSeries>
<ChartSeriesItem
type="bar"
stack={{
type: 'normal',
}}
gap={2}
spacing={0.35}
categoryField="categoryField"
colorField="color"
data={diskData1State}
tooltip={true}
/>
</ChartSeries>
</Chart>
</div>
</>
);
}
enter image description here

Related

How to change react-select option automatically after 5 seconds

I have created a dropdown menu in react using the react-select package, The dropdown menu is working as as expected, now I want to change the option value automatically after some seconds. After some seconds it should select another option from the option array, which option I want from the option array option.
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import Select, { components } from "react-select";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faCircle, faMinusCircle } from "#fortawesome/fontawesome-free-solid";
import "./presence.css";
function Presence() {
const [presence, setPresence] = useState({
value: "unavailable",
label: "Offline",
icon: <FontAwesomeIcon icon={faCircle} color="gray" />,
});
console.log(presence);
const client = useSelector((state) => state.client.client);
const handleChange = (selectedOption) => {
setPresence(selectedOption.label);
console.log(`Option selected:`, selectedOption);
};
const { Option, SingleValue } = components;
const CustomSelectOption = (props) => (
<Option {...props}>
<div style={{ display: "inline-block", marginRight: "5%" }}>
{props.data.icon}{" "}
</div>
<div style={{ display: "inline-block" }}> {props.data.label}</div>
</Option>
);
const ValueOption = (props) => (
<SingleValue {...props}>
<span style={{ marginRight: "8%" }}> {props.data.icon}</span>
<span>{props.data.label}</span>
</SingleValue>
);
const options = [
{
value: "chat",
label: "Available",
icon: <FontAwesomeIcon icon={faCircle} color="#5cd068" />,
},
{
value: "xa",
label: "Appear Away",
icon: <FontAwesomeIcon icon={faCircle} color="orange" />,
},
{
value: "away",
label: "Be Right Back",
icon: <FontAwesomeIcon icon={faCircle} color="orange" />,
},
{
value: "dnd",
label: "Do not Disturb",
icon: <FontAwesomeIcon icon={faMinusCircle} color="red" />,
},
{
value: "unavailable",
label: "Offline",
icon: <FontAwesomeIcon icon={faCircle} color="gray" />,
},
];
const style = {
control: (base) => ({
...base,
border: 0,
boxShadow: "none",
}),
placeholder: (base) => ({
...base,
fontSize: "1em",
fontWeight: 600,
}),
};
const DropdownIndicator = (props) => {
return (
components.DropdownIndicator && (
<components.DropdownIndicator {...props}>
<FontAwesomeIcon
icon={props.selectProps.menuIsOpen ? "caret-up" : "caret-down"}
/>
</components.DropdownIndicator>
)
);
};
return (
<Select
styles={style}
name="presence"
clearable={false}
placeholder={"Choose"}
onChange={handleChange}
options={options}
classNamePrefix="select"
components={{
Option: CustomSelectOption,
SingleValue: ValueOption,
DropdownIndicator: DropdownIndicator,
IndicatorSeparator: () => null,
}}
/>
);
}
export default Presence;
If you want to execute some code after the first render only, use useEffect(() => {}, []) (notice the empty array), to execute once after 5 seconds, call the setTimeout in the callback like this:
useEffect(() => {
setTimeout(() => {
handlerChange(options.find(o => o.value === 'chat'));
}, 5000);
}, []);
You have no value defined on your <Select>
You have no getOptionValue or getOptionLabel defined (though it's probably using the defaults)
If presence were your value, all it would require is the selectedOption.value
Since presence appears to be defaulted to unavailable, then your initial value would never be away
You are rebuilding a lot of stuff on every rerender of Presence, which will force rerender your <Select> every time.
You are defaulting your presence to "unavailable", so it would never start as "away"
Maybe you're saying you will change the value by loading some record on component load. In that situation, you would put your window.setTimeout in that method. I put some notes on that in the comments below.
Refactored Presence.js:
import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import Select, { components } from "react-select";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faCircle, faMinusCircle } from "#fortawesome/fontawesome-free-solid";
import "./presence.css";
const { Option, SingleValue, DropdownIndicator } = components;
const CustomSelectOption = (props) => {
const {
data: { icon: Icon, label }
} = props;
return (
<Option {...props}>
<div style={{ display: "inline-block", marginRight: "5%" }}>
<Icon />{" "}
</div>
<div style={{ display: "inline-block" }}> {label}</div>
</Option>
);
};
const ValueOption = (props) => {
const {
data: { icon: Icon, label }
} = props;
return (
<SingleValue {...props}>
<span style={{ marginRight: "8%" }}>
{" "}
<Icon />
</span>
<span>{label}</span>
</SingleValue>
);
};
const Indicator = (props) => {
const icon = props.selectProps.menuIsOpen ? "caret-up" : "caret-down";
return (
<DropdownIndicator {...props}>
<FontAwesomeIcon
icon={icon}
/>
</DropdownIndicator>
);
};
const Separator = () => null;
const options = [
{
value: "chat",
label: "Available",
icon: <FontAwesomeIcon icon={faCircle} color="#5cd068" />
},
{
value: "xa",
label: "Appear Away",
icon: <FontAwesomeIcon icon={faCircle} color="orange" />
},
{
value: "away",
label: "Be Right Back",
icon: <FontAwesomeIcon icon={faCircle} color="orange" />
},
{
value: "dnd",
label: "Do not Disturb",
icon: <FontAwesomeIcon icon={faMinusCircle} color="red" />
},
{
value: "unavailable",
label: "Offline",
icon: <FontAwesomeIcon icon={faCircle} color="gray" />
}
];
const style = {
control: (base) => ({
...base,
border: 0,
boxShadow: "none"
}),
placeholder: (base) => ({
...base,
fontSize: "1em",
fontWeight: 600
})
};
const getLabel = (option) => option.label;
const getValue = (option) => option.value;
function Presence() {
const [presence, setPresence] = useState("unavailable");
console.log(presence);
const client = useSelector((state) => state.client.client);
/**
* Let's say you include some other process to 'set' `presence`,
* like loading some record or something. The you could 'init'ialize
* your component by then adding your timeout. You can't really do
* this alone in a `useEffect`, as you defaulted the value, which
* would trigger your effect.
*
window.setTimeout(() => {
// make sure to check that current value again, in case
// someone changed it in that 5 seconds
setPresence(prev => prev === 'away' ? 'chat' : prev);
}, 5000);
*/
const handleChange = (selectedOption) => {
setPresence(selectedOption?.value);
console.log(`Option selected:`, selectedOption);
};
return (
<Select
styles={style}
name="presence"
isClearable={false}
placeholder={"Choose"}
onChange={handleChange}
options={options}
classNamePrefix="select"
components={{
Option: CustomSelectOption,
SingleValue: ValueOption,
DropdownIndicator: Indicator,
IndicatorSeparator: Separator
}}
getOptionLabel={getLabel}
getOptionValue={getValue}
value={presence}
/>
);
}
export default Presence;

how to increment value by +1 by clicking button in react js

am stuck with a problem when I click on like button I want it increment by +1, can anyone tell me how can I do it, I try it but I can't solve it.
below I share my all code that I used to make my small application. if you have question free feel to ask me.
Music.js
This is my music form where I wrote my whole code.
import React, { useState, useRef, useEffect } from 'react';
import { makeStyles } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import Button from '#material-ui/core/Button';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import ExitToAppIcon from '#material-ui/icons/ExitToApp';
import RadioIcon from '#material-ui/icons/Radio';
import firebase from '../Firebase';
import SearchBar from "material-ui-search-bar";
import { useHistory } from 'react-router-dom';
import { Container, Input, TextField } from '#material-ui/core';
import './Music.css';
import Table from '#material-ui/core/Table';
import TableBody from '#material-ui/core/TableBody';
import TableCell from '#material-ui/core/TableCell';
import TableContainer from '#material-ui/core/TableContainer';
import TableHead from '#material-ui/core/TableHead';
import TableRow from '#material-ui/core/TableRow';
import Paper from '#material-ui/core/Paper';
import ThumbUpAltIcon from '#material-ui/icons/ThumbUpAlt';
// import { useSelector } from 'react-redux';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
search: {
marginTop: 30,
},
table: {
minWidth: 650,
marginBottom: 10,
},
cells: {
marginTop: 50,
},
thumb: {
color: '#e75480',
},
name: {
color: 'blue',
padding: 10,
fontSize: 20,
},
audios: {
display: 'flex',
margin: 'auto',
height: 50,
width: 500,
alignItems: 'center'
},
icon: {
fontSize: 40,
color: '#e75480',
cursor:'pointer'
}
}));
const Music = () => {
const history = useHistory();
const inputRef = useRef(null);
const [search, setSearch] = useState("");
const [like, setLike] = useState(false);
const [music,setMusics] = useState([
{
id:"1",
name:"Arijit singh",
audiosrc:"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
},
{
id:"2",
name:"Atif Aslam",
audiosrc:"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
},
{
id:"3",
name:"Sonu Nigam",
audiosrc:"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
},
{
id:"4",
name:"Neha kakkar",
audiosrc:"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
},
])
const likeButton = (id)=>{
const likebuttons = music.find((curElem)=>{
return curElem.id == id
})
setLike({likebuttons:like+1})
console.log(likebuttons);
}
console.log(search);
// Logout Functionality
const Logout = () => {
firebase.auth().signOut().then(() => {
alert("Logout Successfull...");
history.push('/');
}).catch((error) => {
console.log(error);
});
}
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static" style={{ width: '100%' }}>
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<RadioIcon style={{ fontSize: "30px" }} /> React Music
</IconButton>
<Typography variant="h6" className={classes.title}>
</Typography>
<Button color="inherit" onClick={Logout}> <ExitToAppIcon /> Logout </Button>
</Toolbar>
</AppBar>
<Container>
<SearchBar className={classes.search}
value={search}
onChange={(newValue) => setSearch(newValue)}
/>
<Table className={classes.table} aria-label="simple table">
<TableBody>
{music && music.map(mus=>{
return(
<TableRow>
<TableCell style={{ display: 'flex', justifyContent: 'space-around' }}>
<div>
<h3>{like} <ThumbUpAltIcon className={classes.icon} onClick={()=>likeButton(music.id)} /> {mus.name}</h3>
</div>
<div>
<audio ref={inputRef} src={mus.audiosrc} className={classes.audios} controls />
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Container>
</div>
);
}
export default Music;
Make following changes in your code:
const [like, setLike] = useState(false);
to
const [like, setLike] = useState(0);
and
setLike({likebuttons:like+1})
to
setLike(like+1);
and try again.
If you want to have like count for all music data,
First you should change like state to store object
const [like, setLike] = useState({});
Change your like button function to store data in object
const likeButton = (musicId)=>{
setLike({...like, like[musicId]: like[musicId] + 1 || 1 })
}
Now change how you are showing like count as below:
<div>
<h3>{like[music.id]} <ThumbUpAltIcon className={classes.icon} onClick={()=>likeButton(music.id)} /> {mus.name}</h3>
</div>
first, you should change your states.
each music has it's own like number, so you can't use 1 like state for all.
each item in your music array should have a value to store it's own like
numbers.
something like :
const [music,setMusics] = useState([
{
id:"1",
name:"Arijit singh",
audiosrc:"https://uploa...",
likeNumbers:0,
},
...
]
then your onClick should iterate the music array, find the clicked item and change it's likeNumbers value.
something like this:
cosnt handleClick = (id) => {
setMusic((prevState) => prevState.map((item) => {
if (item.id === id ) {
return {...item, likeNumbers:likeNumbers + 1 }
} else {
return item
}
})
}
to be clear:
first you should take the last version of your state, then in the process of iterating, find the clicked item and update it. to avoid mutate your state ( because items are objects ), you should make a copy first, then changed it. I mean here:
return {...item, likeNumbers:likeNumbers + 1 }
after all a part of your jsx code should be changed to :
<h3>{mus.likeNumber} <ThumbUpAltIcon className={classes.icon} onClick={()=>likeButton(music.id)} /> {mus.name}</h3>
First you need to make type as number instead of boolean
const [like, setLike] = useState(0);
and then
const likeButton = (id)=>{
const likebuttons = music.find((curElem)=>{
return curElem.id == id
})
setLike(likebuttons+1);
console.log(likebuttons);
}
Or
you can add no. of likes in same array object and just update that like field
You can check below example created for you. I hope it will help you.
It's having only like functionality
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [likedSong, setLikedSong] = useState({
likes: 0,
id: 0
});
const [music, setMusics] = useState([
{
id: "1",
name: "Arijit singh",
audiosrc:
"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
likes: 0
},
{
id: "2",
name: "Atif Aslam",
audiosrc:
"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
likes: 0
},
{
id: "3",
name: "Sonu Nigam",
audiosrc:
"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
likes: 0
},
{
id: "4",
name: "Neha kakkar",
audiosrc:
"https://upload.wikimedia.org/wikipedia/commons/1/15/Bicycle-bell.wav",
likes: 0
}
]);
const handleLike = (list) => {
if (likedSong.id === list.id) {
setLikedSong({ ...likedSong, id: list.id, likes: ++likedSong.likes });
} else {
setLikedSong({ ...likedSong, id: list.id, likes: 0 });
}
};
return (
<div className="App">
{music.map((mus) => (
<div key={mus.id} className="music-list">
<div>
{mus.id === likedSong.id && (
<span className="no-likes">{likedSong.likes}</span>
)}
<span className="btn-like" onClick={() => handleLike(mus)}>
Like
</span>
{mus.name}
</div>
</div>
))}
</div>
);
}
Live working demo

"react-useanimations" Property 'animationKey' does not exist on type 'IntrinsicAttribute

I have used "react-useanimations" plugin, when i run my project showing me the following error.
Property 'animationKey' does not exist on type 'IntrinsicAttribute
common.js-> common functions are written here (simple js file)
myjob.tsx-> actual getTag function used on this page (typescript page)
// Common.js file
import React from "react";
import UseAnimations from "react-useanimations";
export function getTag(tag: any) {
if (tag === 'DL')
return (
<UseAnimations animationKey="github" size={56} style={{ padding: 100 }} />
);
}
// myjob.tsx
import React, { useState, useEffect } from "react";
import SVG from "react-inlinesvg";
import { Link } from "react-router-dom";
import { Alert, Nav, Tab } from "react-bootstrap";
import { toAbsoluteUrl } from "../../_metronic/_helpers";
import { utcToDate, getTag } from "../../utils/common";
import Icon from '#material-ui/core/Icon';
import { MDBDataTableV5 } from 'mdbreact';
import { Dropdown, Button } from "react-bootstrap";
import { DropdownCustomToggler } from "../../_metronic/_partials/dropdowns";
import Paper from '#material-ui/core/Paper';
import Draggable from 'react-draggable';
import { getUserJobList, deleteJobById } from "../../app/modules/Job/_redux/jobCrud";
import { shallowEqual, useSelector } from "react-redux";
export function MyJobs(props: any) {
const [open, setOpen] = React.useState(false);
const [openSnackbar, setOpenSnackbar] = React.useState(false);
const [deleteJobId, setDeleteJobId] = useState("");
const [key, setKey] = useState("Month");
const [msg, setMsg] = useState("")
const [type, setType] = useState<"success" | "primary" | "secondary" | "danger" | "warning" | "info" | "dark" | "light" | undefined>("success")
const [jpbList, setJpbList] = useState([])
const [displayBy, setDisplayBy] = useState(false)
const [folders, setFolders] = useState()
const user = useSelector((state: any) => state.auth.user, shallowEqual);
const [datatable, setDatatable] = useState({
columns: [
{
label: '#',
field: 'icon',
width: 150,
attributes: {
'aria-controls': 'DataTable',
'aria-label': 'Name',
},
},
{
label: 'Job Name',
field: 'name',
width: 150,
attributes: {
'aria-controls': 'DataTable',
'aria-label': 'Name',
},
},
{
label: 'Proccesed Date',
field: 'createdDttm',
width: 270,
},
{
label: 'Status',
field: 'status',
width: 270,
},
{
label: 'Action',
field: 'action',
width: 270,
},
],
rows: [{}],
});
useEffect(() => {
if (!jpbList.length) {
getList();
}
}, []);
const getList = async () => {
getUserJobList(user.id)
.then((res: any) => {
if (res.status == 200 && res.data) {
let rows: any = [];
res.data.map((row: any) => {
rows.push(
{
icon:<img src={row.thumbnail} style={{ maxWidth: '50px', maxHeight: '50px' }} />,
name: row.name,
createdDttm: utcToDate(row.createdDttm),
status: getTag(row.status),
action: <div style={{ width: '120px' }}>
{/* begin::Toolbar */}
<div className="d-flex justify-content-end">
{
row.status == "CO" ?
<Link to={`myjobs/markerpage/${row.id}`} className="btn btn-icon btn-sm mx-3">
<span className="svg-icon svg-icon-md svg-icon-primary">
<Icon className='fa fa-play' color="action" />
</span>
</Link> : ""
}
< Dropdown className="dropdown dropdown-inline" alignRight>
<Dropdown.Toggle
id="dropdown-toggle-top-user-profile"
as={DropdownCustomToggler}
>
<i className="ki ki-bold-more-hor"></i>
</Dropdown.Toggle>
<Dropdown.Menu className="dropdown-menu dropdown-menu-sm dropdown-menu-right">
</Dropdown.Menu>
</Dropdown>
</div>
{/* end::Toolbar */}</div >,
}
)
});
let dt: any = [];
dt.columns = datatable.columns;
dt.rows = rows;
setDatatable(dt);
setJpbList(res.data);
} else {
setMsg("Something went wrong please try again later.")
setType("danger")
}
})
.catch((e: any) => {
setMsg("Something went wrong please try again later.")
setType("danger")
});
}
return (
<>
<MDBDataTableV5 hover entriesOptions={[10, 20, 50]} entries={10} pagesAmount={4} data={datatable} searchTop searchBottom={false} />
</>);
}
First import icon which you want.
import UseAnimations from "react-useanimations";
import activity from 'react-useanimations/lib/activity'
In view or in render use like this
<UseAnimations animation={activity} autoplay={true} loop={true} size={20} style={{ paddingLeft: 10 }} />

Is there is way to set pagination arrows to be enabled even there is no data?

how can i set pagination arrows to be enabled even there is no data or even if i'll use a condition to switch disable/enablePagination Arrows
import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { NavLink } from 'react-router-dom';
import Truncate from 'react-truncate';
// Material-UI
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import AddIcon from '#material-ui/icons/Add';
import EditIcon from '#material-ui/icons/Edit';
import MaterialTable, { MTableToolbar, TablePagination } from 'material-table';
import IconButton from '#material-ui/core/IconButton';
import Tooltip from '#material-ui/core/Tooltip';
import Typography from '#material-ui/core/Typography';
import Zoom from '#material-ui/core/Zoom';
// Components
import Entity from '~/Components/Entity';
import violationsStyles from './styles';
import Strings from '~/Services/Strings';
// Services
import Navigate from '~/Services/Navigate';
#withStyles(violationsStyles)
class Violations extends React.Component {
state = {
data : [],
pageIndex: 0,
pageSize: 1,
totalCount: 0
}
componentDidMount() {
this.get();
}
get() {
const { pageIndex, pageSize } = this.state;
this.entity.get({ pageIndex, pageSize });
}
get options() {
return {
actionsColumnIndex: -1,
pageSize: 10,
filtering: true,
columnsButton: true,
maxBodyHeight: 550,
doubleHorizontalScroll: true,
headerStyle: {
color: '#434343',
fontSize: 13
}
};
}
get localization() {
return {
header: {
actions: '',
},
body: {
emptyDataSourceMessage: Strings.listEmptyLabel,
},
pagination: {
labelRowsPerPage: Strings.rowsPerPageLabel,
labelDisplayedRows: `{from}-{to} ${Strings.fromText} {count}`,
},
toolbar: {
addRemoveColumns: Strings.addRemoveColumns,
showColumnsTitle: Strings.showColumnsTitle
},
};
}
get columns() {
const { classes } = this.props;
return [
{ title: Strings.violationReferenceNumber, field: 'referenceNumber', cellStyle: { width: 110 } },
{
title: Strings.violationDescription,
field: 'description',
render: rowData => (
<Typography>
<Truncate lines={1} ellipsis={<span>... </span>}>
{rowData.description}
</Truncate>
</Typography>
),
cellStyle: { paddingLeft: 0 }
},
{ title: Strings.violationPenalty,
field: 'penaltyTypeId',
lookup: {
1: Strings.inform,
2: Strings.alert,
3: Strings.suspension,
},
cellStyle: { width: '120px' }
},
{
title: Strings.violationStatus,
field: 'isArchived',
lookup: {
false: Strings.violationIsNotSettled,
true: Strings.violationIsSettled,
},
cellStyle: { width: '130px' },
defaultFilter: [ 'false' ]
},
{
title: Strings.listActionsLabel,
field: 'isArchived',
render: rowData => (
<div className={classes.iconWrapper}>
<Choose>
<When condition={rowData.isArchived === 'true'}>
<Tooltip TransitionComponent={Zoom} title={Strings.violationEditActionOn}>
<span>
<IconButton disabled={rowData.isArchived === 'true'}>
<EditIcon fontSize="default"/>
</IconButton>
</span>
</Tooltip>
</When>
<Otherwise>
<IconButton disabled={rowData.isArchived === 'true' ? true : false} onClick={() => Navigate.go(`/violations/editor/${rowData.id}`)}>
<Tooltip TransitionComponent={Zoom} title={Strings.violationListEditLabel}>
<EditIcon fontSize="default"/>
</Tooltip>
</IconButton>
</Otherwise>
</Choose>
</div>
),
filtering: false,
cellStyle: { paddingLeft: 35, paddingRight: 75, textAlign: 'left', justifyContent: 'flex-end', display: 'flex' },
headerStyle: { paddingLeft: 35, textAlign: 'left', }
},
];
}
get components() {
const { classes } = this.props;
return {
Toolbar: props => (
<div className={classes.toolbar}>
<MTableToolbar {...props} />
<div className={classes.customActionsBar}>
<Button component={NavLink} to={'/violations/editor'} variant={'outlined'} color={'primary'}>
<AddIcon className={classes.rightIcon} />
{Strings.addNewViolation}
</Button>
</div>
<div className={classes.tabelSecondHeader}>
<Typography variant='h6'>
{Strings.listOfViolations}
</Typography>
</div>
</div>
),
Pagination: props => (
<TablePagination {...props}
count={this.state.totalCount}
/>
),
};
}
onEntityReceived(data) {
const arr = data.result;
const mutableList = [];
if(arr && arr.length > 0) {
arr.map(item => {
mutableList.push({
...item,
isArchived: item.isArchived.toString()
});
});
this.setState({
data: mutableList,
totalCount: data.totalCount
});
}
}
render() {
const { data } = this.state;
return (
<React.Fragment>
<Helmet>
<title>
{Strings.violationsManegment}
</title>
</Helmet>
<Entity
storeId={'Supervision-Violations'}
entityRef={ref => { this.entity = ref; }}
onEntityPosted={() => this.onEntityPosted()}
onEntityReceived={data => this.onEntityReceived(data)}
render={store => (
<MaterialTable
title={Strings.violationsManegment}
data={data}
isLoading={store.loading}
options={this.options}
localization={this.localization}
columns={this.columns}
components={this.components}
onChangePage={pageIndex => this.setState({ pageIndex })}
onChangeRowsPerPage={pageSize => this.setState({ pageSize })}
/>
)}
/>
</React.Fragment>
);
}
}
Violations.propTypes = {
classes: PropTypes.object,
};
export default Violations;
i need to update the count of table because i'm getting the data from back-end and i'm using server side pagination technique and it appears that the total counts automatically be the total rows received unless i mutated it to be be total count that i received from endpoint because i receive some data per page
Use nextIconButtonProps={{disabled:false}} and backIconButtonProps={{disabled:false}}
could you try using the override that is explained here https://material-table.com/#/docs/features/component-overriding.
Use the code above to try to find a way of that you want. Right now there isnt a property that you can do that in a easy way.
components={{
Pagination: props => (
<TablePagination
{...props}
rowsPerPageOptions={[5, 10, 20, 30]}
rowsPerPage={this.state.numberRowPerPage}
count={this.state.totalRow}
page={
firstLoad
? this.state.pageNumber
: this.state.pageNumber - 1
}
onChangePage={(e, page) =>
this.handleChangePage(page + 1)
}
onChangeRowsPerPage={event => {
props.onChangeRowsPerPage(event);
this.handleChangeRowPerPage(event.target.value);
}}
/>
),
}}

react-charts "stacked:true" is not working

I've created a chart in ReactJS using react-charts, with multiple bars.
This is my component:
import React, { Component } from "react";
import { Chart } from "react-charts";
import axios from "axios";
const qs = require("qs");
class Volume extends Component {
state = {
load_vol_chart: true,
volume_chart_data: []
};
componentDidMount() {
this.getVolumeChartData();
}
getVolumeChartData() {
var name = this.props.name;
axios
.post(
`http://api.mydomain.in/details/`,
qs.stringify({ type: name })
)
.then(res => {
if (res.data.result === 1) {
this.setState({
volume_chart_data: [
{
label: "Label1",
data: res.data.data2.map(vol => ({
x: vol.created_at,
y: (vol.volume * vol.percentage) / 100
}))
},
{
label: "Label2",
data: res.data.data2.map(vol => ({
x: vol.created_at,
y: vol.volume
}))
}
],
load_vol_chart: false
});
}
});
}
render() {
return (
<div className="inner-content" style={{ marginTop: "12px" }}>
<h3>
<i className="fa fa-caret-right" /> {" "}
{this.props.symbol}: Volume
</h3>
{this.state.load_vol_chart ? null : (
<div
style={{
width: "100%",
height: "400px",
marginTop: "35px",
marginBottom: "10px"
}}
>
<Chart
data={this.state.volume_chart_data}
series={{ type: "bar" }}
axes={[
{ primary: true, type: "ordinal", position: "left" },
{ position: "bottom", type: "linear" }
]}
primaryCursor
secondaryCursor
tooltip
/>
</div>
)}
</div>
);
}
}
export default Volume;
What I want is:
The Label1 bar is calculated with some formula. In charts tooltip, I want to display a additional value like: vol.percent. Also Can I show this percent on bar as a label on it?
I want these charts to stacked. I've tried stacked:true, it's not working.
How can I achieve these?
Thanks in advance.

Resources