Topic: how to add conditional css to <td> in mdbdatatable where data is provided as json from api
vickrant shinde asked 3 years ago
I created a mdbdatatablev5 with data from an api. and i want the td where values is greater than zero to be added with some css. currently there is no direct way possible for that. so how can i achieve it..?
Krzysztof Wilk staff answered 3 years ago
Hi!
You can use a little bit of JavaScript to achieve that. An example I've created below should be helpful :)
import React, { useEffect } from 'react';
import { MDBContainer, MDBRow, MDBCol, MDBCard, MDBCardBody, MDBDataTableV5 } from 'mdbreact';
const DatatablePage = () => {
const data = {...};
useEffect(() => {
setTimeout(() => {
const tableCard = document.getElementById('test');
const rows = tableCard.querySelectorAll('tr');
rows.forEach((row) => {
const val = parseInt(row.children[3].textContent);
if (!isNaN(val) && val > 40) {
row.children[3].style.backgroundColor = 'red';
}
});
}, 4)
});
return (
<MDBContainer className='mt-3'>
<MDBRow className='py-3'>
<MDBCol md='12'>
<MDBCard>
<MDBCardBody id='test'>
<MDBDataTableV5
hover
entriesOptions={[5, 20, 25]}
entries={5}
pagesAmount={4}
data={data}
searchTop
searchBottom={false}
/>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
);
};
export default DatatablePage;
Keep coding!
vickrant shinde commented 3 years ago
the issue with this code is when a column is arranged in Ascending or descending order the value changes but the css remains as it is.
Krzysztof Wilk staff answered 3 years ago
Hi!
You can move this setTimeout into the function and apply it to every item on the page you want. Consider code below :)
const handleSort = () => {
setTimeout(() => {
const tableCard = document.getElementById('test');
const rows = tableCard.querySelectorAll('tr');
rows.forEach((row) => {
const val = parseInt(row.children[3].textContent);
if (!isNaN(val) && val > 40) {
row.children[3].style.backgroundColor = 'red';
} else {
row.children[3].style.backgroundColor = 'white';
}
});
}, 4);
};
useEffect(() => {
handleSort();
const itemsToHandle = ['.page-item', '.sorting', '.sorting_asc', '.sorting_desc'];
itemsToHandle.forEach((item) => {
document.querySelectorAll(item).forEach((el) => el.addEventListener('click', handleSort));
});
return () => {
itemsToHandle.forEach((item) => {
document.querySelectorAll(item).forEach((el) => el.removeEventListener('click', handleSort));
});
};
}, []);
Keep coding!
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB React
- MDB Version: MDB4 5.0.1
- Device: dell
- Browser: all
- OS: windows 10
- Provided sample code: No
- Provided link: No