Autoheight in MUI DataGrid - css

I'm using the MUI DataGrid component, and the behavior I hope to have is that:
When there's a small number of rows, the table is only the size it needs to for those rows.
When there's a large number of rows, more than the current viewport can hold (given whatever else is on the screen), the table takes up the available space in the layout (given its flex: 1) and the extra rows scroll inside the table.
I can achieve each of these behaviors, but only one at a time.
If I use the autoHeight property on the DataGrid, then the table will be as small as it can be. BUT it will also be as big as it can be, so with a large number of rows the container scrolls the entire table, rather than the rows scrolling within the table.
If I don't use autoHeight, and wrap the DataGrid in a container with flex: 1, then the table will grow to fill the available space and the rows will scroll within the table. BUT a table with only a few rows will also grow to fill its container, so that there is empty space under the rows (above the footer, "Table rows: #")
You can see the situation in this screenshot, showing the exact same page, with different data.
I've tried what feels like every permutation of heights and flexes under the sun. For example:
Setting autoHeight with a maxHeight (and .MuiDataGrid-main { overflow: scroll; } ) allows few-rows to be small, and many-rows to be not too small, but obviously any discrete maxHeight, be it px or %, is not the flexible layout I'm going for.
Turning off autoHeight (as in scenario #2) and setting flex-grow: 0 on the rows container within the table (.MuiDataGrid-main) just makes the rows disappear since they then shrink to a height of 0.
The code for the component:
const S = {
Wrapper: styled.div`
width: 100%;
display: flex;
flex: 1;
background: white;
border: solid thick red;
`,
DataGrid: styled(DataGridPro)`
&& {
.MuiDataGrid-main {
//overflow: scroll;
//flex-grow: 0;
}
background: lightgreen;
font-size: 14px;
}
`,
};
type Props = {
columns: ReadonlyColumns;
rows: AnyObject[];
filterModel?: GridFilterModel;
} & Omit<DataGridProps, 'columns'>;
const DataTable: React.FC<Props> = ({
columns = [],
rows = [],
filterModel,
className,
...props
}) => {
const memoizedColumns = useMemo(
() =>
columns.map(col => ({
headerClassName: 'columnHeader',
flex: 1, // all columns expand to fill width
...col, // but could override that behavior
})),
[columns],
);
return (
<S.Wrapper className={className}>
<S.DataGrid
// autoHeight
rows={rows}
columns={memoizedColumns}
filterModel={filterModel}
{...props}
/>
</S.Wrapper>
);
};

Using a combination of autoHeight and pageSize will create a table whose height is only as big as needed for the current number of rows as long as the number of rows is <= pageSize. Additional rows will be added to a new page.
<DataGrid
rows={rows}
columns={columns}
pageSize={20} //integer value representing max number of rows
autoHeight={true}
/>

Below solved the issue:
<DataGrid getRowHeight={() => 'auto'} />
Source:
https://mui.com/x/react-data-grid/row-height/#dynamic-row-height

I had a similar issue days ago and I solved recalculating the row height every time a new item was added to my row.
getRowHeight={(props: GridRowHeightParams) => {
const serviceRowHeight = 45 // <-- default height, if I have no data for the row
const addServiceBtnHeight = 45 // <-- a component that's always on the row
const height = props.model?.services // services is each dynamic item for my row, so you should access like props.yourObj
? props.model.services.length * serviceRowHeight + addServiceBtnHeight
: 115
return height < 115 ? 115 : height // final height to be returned
}}

Related

React: Only display items which fully fit within flex box, and dynamically determine the number of items being displayed

The accepted answer here is very very close to being what I want. I have a vertical flexbox with items that have a fixed height. I would like as many items as possible to be displayed, but if an item overflows at all, it should be completely omitted. Try the code snippet in the linked answer to see what I mean. This effect can pretty easily be achieved by setting 'flex-wrap: wrap' and overflow hidden on the container.
However, I have one more issue: instead of just displaying these items, I also need to know HOW MANY are currently being displayed. I'm trying to show as many items as will fit, and then at the bottom a label will say "...and 5 more" if there are five items that don't fit, for example. What's the easiest way to go about this? I would love to avoid just dividing the height of the container by the heights of the individual items if possible. There must be a better way.
Did a lot of digging and finally came to a solution that I'm happy with. Use offsetLeft of the elements in order to determine which ones are wrapped. Do the same but with offsetTop for a horizontal flex box.
CSS:
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
React:
const items = [...]; // Array of ReactElements
const [numberOfItemsDisplayed, setNumberOfItemsDisplayed] = useState(0);
const ref = useRef(null)
useLayoutEffect(() => {
const cells = ref.current?.children;
if (cells && cells.length > 0) {
const startingOffset = cells[0].offsetLeft;
let numItems = 0;
for (let i = 0; i < cells.length; i++) {
if (cells.offsetLeft > startingOffset) {
break;
}
numItems++;
}
setNumberOfItemsDisplayed(numItems);
}
}, []);
return <div class="container" ref={ref}>{items}</div>

CanvasJS charts take up entire row when using flexbox

I am currently using CanvasJS for pie charts in a project done in ReactJS. When a search for a particular person is done, I render 4 pie charts displaying information. I would like to render the pie charts side-by-side (as the space allows) over multiple rows using Flexbox.
Currently, when the pie charts render, each CanvasJSChart takes up the entire width of the row. In the picture below, you can see that although each pie chart takes up ~1/3 of of the table (the "Trial Version" and "Canvasjs.com" are not fixed in position relative to the pie chart and can move closer to it, depending on the size of the container), the container is the width of the row. I would ideally like each row to contain 2 pie charts (but not fixed to allow the application to work better on small screens).
This is my CSS section.
.container {
display:flex;
flex-wrap: row wrap;
}
When I did not have the flex-wrap: row wrap; line, the charts would individually take up less space and all remain on the same row:
So when I do try to have the charts wrap around, I'm not sure why the size of the container changes to the entire row. Below is my code that renders the charts (in a component named Accuracy when I search a name:
class Contestant extends Component{
constructor(props){
super(props)
}
render(){
var name = this.props.data[0];
var data = this.props.data[1];
let fjText = null
let fj = null
if (data.FJCorrect+data.FJIncorrect>0){
fj = <Accuracy numberCorrect={data.FJCorrect} numberIncorrect={data.FJIncorrect}
overallAccuracy = {data.FJAccuracy}/>
}
let tiebreak = null
let tiebreakText = null
if (data.TiebreakCorrect+data.TiebreakIncorrect>0){
tiebreak = <Accuracy numberCorrect={data.TiebreakCorrect}
numberIncorrect={data.TiebreakIncorrect}overallAccuracy = {data.TiebreakAccuracy} />
}
return(
<div className = "container" >
<Accuracy numberCorrect={data.numberCorrect} numberIncorrect={data.numberIncorrect}
overallAccuracy = {data.overallAccuracy}/>
<Accuracy numberCorrect={data.JCorrect} numberIncorrect={data.JIncorrect}
overallAccuracy = {data.JAccuracy}/>
<Accuracy numberCorrect={data.DJCorrect} numberIncorrect={data.DJIncorrect}
overallAccuracy = {data.DJAccuracy}/>
{fj}
{tiebreak}
</div>
)
}
}
export default Contestant
and below is my code that renders a Contestant component:
class Search extends Component{
constructor(){
super()
this.state = {search: "",
isLoading: true,
result: "",
searchType: null
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSearch = this.handleSearch.bind(this);
}
handleSearch(searchStr){
//Takes in text and finds data of corresponding person
}
handleChange(event){
//In case someone is searching for a new term, we have to reset search query type
if (this.state.searchType !== null){
this.setState({isLoading: true})
}
this.setState({search: event.target.value});
}
handleSubmit() {
this.setState({isLoading: false, result: this.handleSearch(this.state.search)})
}
render(){
return(
<div>
<input type="text" value={this.state.search} onChange={this.handleChange} placeholder={...} />
<button type="submit" onClick={this.handleSubmit}>Search</button>
{this.state.result.length === 0 ? null: <Contestant data={this.state.result}/>}
</div>
)
}
}
export default Search
My CanvasJS pie chart has the default settings as on the linked website (with only data points changed), so I'm not sure why the size of the charts change depending on whether I wrap my Flexbox cells.
class Accuracy extends Component{
constructor(props){
super(props)
}
render(){
var correctAccuracy = ((this.props.overallAccuracy).toFixed(2)).toString()
var incorrectAccuracy = ((100-this.props.overallAccuracy).toFixed(2)).toString()
var options = {
animationEnabled: false,
animationEnabled: true,
animationDuration: 500,
backgroundColor: "#F0F8FF",
height: 260,
data: [{
type: "pie",
startAngle: 300,
toolTipContent: "{accuracy}%",
indexLabelFontSize: 16,
indexLabel: "{label}:{y}",
dataPoints: [
{ y: this.props.numberCorrect, label: "Correct", accuracy: correctAccuracy },
{ y: this.props.numberIncorrect, label: "Incorrect", accuracy: incorrectAccuracy},
]
}]
}
return (
<CanvasJSChart options = {options}/>
)
}
}
export default Accuracy
Any help would be greatly appreciated! I've been stuck on this for a couple of days
From the first screencap, it seems like your problem is that the width of your pie chart containers is set to 100%. This means that each container will be 100% of its parent--in this case the .container div. Your CSS should look like this:
.container {
display: flex;
flex-wrap: row-wrap;
}
.piechart-container {
width:50%;
}
And of course you need to add the "piechart-container" classname to you piechart container divs. I didn't try this out so let me know if it works. You may have to set the width to be slightly less than 50% or change the max-width property as well. Instead of width:50% you could do flex:0 0 50% which is a flexbox item property meaning "set an initial width of 50% and don't allow any growing or shrinking."
Edit: just now seeing that you want some flexibility. You'd probably be better off setting the container widths in terms of pixels instead of percentages so that when the screen gets small enough they overflow to be one chart per row. I would recommend looking up "media queries" and setting the CSS so that if the screen width goes below a certain number, a different set of attributes takes place (i.e. smaller charts, different wrapping behavior)

How to wrap a long text in table cell (react-bootstrap-table-next)?

I am introduced to react/redux/sagas/redux-form web application development. I used react-bootstrap-table-next in order to display data in a table format.
It has two columns as Title, Description however data for Title column is a long string data.
foo1,foo2,foo3,foo4,foo5,foo6,foo7 bar
And the problem I am having is it overflows or occupies cell/row under Description so that data under Description column is masked.
I tried something like this but it didn't make a difference.
const rowStyle = (row, rowIndex) => {
return { whiteSpace: 'pre-line'; };
};
<BootstrapTable data={ data } columns={ columns } rowStyle={ rowStyle } />
What would be the way to wrap this long string so that it can be contained within fixed width of cell under Title column?
[update]
Found an answer with following css instead.
return { overflowWrap: 'break-word' };
You can do it by providing certain styling in your tag.
<BootstrapTable data={data} bodyStyle={ {width: 500, maxWidth: 500, wordBreak: 'break-all' } }>

Is there a way to detect when a row changed with a UL of float-lefted LIs?

Here's an example list I have of products: http://imgur.com/7IGthIa
I've got a function that runs on document-ready that cycles through each list and adjusts the height of a span around the img, so that the space is uniform throughout the entire list.
What I'm wondering is, is there a way to have it detect when the "row" changes, so that the spans appear as-is on the first row (as they're sized appropriately based on the first two, but on the second row, with the single entry, the span is the height of THAT image?
The function does the same thing with the height of the LI elements, and I'll probably adjust it to size this per row as well, if there's a workable solution.
This is the function it runs to calculate the height, if it's of any use:
if ( jQuery('.product_list').length ) {
var tallest = 0;
var tallest_img = 0;
jQuery('.product_list li').each( function() {
if ( jQuery(this).height() > tallest ) { tallest = jQuery(this).height(); }
if ( jQuery(this).children('a').children('span').children('img').height() > tallest_img ) {
tallest_img = jQuery(this).children('a').children('span').children('img').height();
}
});
jQuery('.product_list li').height( tallest );
jQuery('.product_list li span').height( tallest_img );
}
Thanks!
You can detect when a row changes by checking an element's offset().top.
Since you're setting heights on the spans, I'll assume they have a style of display: inline-block. (You can't set the height of an inline element.)
Since the spans are children of the lis, you shouldn't have to worry about setting the li heights (unless I misunderstood your question).
This code iterates through the spans, giving them equal heights per row based on the tallest img within each row:
function sizeSpans() {
var spans= $('ul span'),
tallest,
top= $(spans[0]).offset().top;
spans.css('height', '');
tallest= $(spans[0]).height();
spans.each(function(idx1) {
if($(this).offset().top === top) {
tallest= Math.max(tallest, $(this).height());
spans.each(function(idx2) {
if(idx2 <= idx1 &&
$(this).offset().top === top
) {
$(this).css('height', tallest);
}
});
}
else {
tallest= $(this).height(),
top= $(this).offset().top;
}
});
} //sizeSpans
You can add this to a resize handler:
$(window).resize(sizeSpans);
Working Fiddle
Click the Size spans button at top. Resize the frame to see sizes readjust.

angular ng-grid maxWidth not used

I am trying to create some autosizing properties for an angular ng-grid element:
for (var i = 0; i < $scope.dates.length; i++) {
var dateElement = {
field: 'reportMap.' + $scope.dates[i] + '.hours | round',
displayName: i + 1,
minWidth: "27px",
maxWidth: "46px"
};
if ($scope.holidays.indexOf(i + 1) != -1) {
dateElement.cellTemplate = 'app/partials/gridCell.html';
}
$scope.columns.push(dateElement);
.....
$scope.gridOptions = {
data: 'monthlyReports',
columnDefs: 'columns',
plugins: [new ngGridFlexibleHeightPlugin()],
enableRowSelection: false,
enableColumnResize: true,
enableSorting: false,
enableCellSelection: true
};
However, when the field data gets longer than 4 characters the content is hidden. I.e. the width is not increased. I could be using width: "auto" but i need to limit the sizing of th columns somewhat...
Why is the column width not increased when the conent gets longer than 27px?
This is what i get setting the width to auto for my date elements:
This is what i want, dynamic width depending on content! (i also want less padding around the number and the left and right sides of the cell, see the wide cell)
Ovveriding the cell properties did the trick in this case, just increasing the constant width one pixel to 28px and overriding the padding made it look good.
ngCellText {padding: 2px; text-align: center;}

Resources