Col Width Resizing

Tags: #<Tag:0x00007efc71a26290> #<Tag:0x00007efc71a26150>

Please help me find out what is wrong I am doing.

I am simply trying to have the cols width adjusted to be auto and match the longest cell text:

as you can see how the colwidth here not expanded enough:

My dreeeeam to see it like the following without adjusting manually

I tried:

 colWidths: [900, 900, 400, 900, 50],

and
colWidths: [null, null, null, null, null],
and
autoColumnSize: true,

and
afterRender: function() {
this.updateSettings({ autoColumnSize: true });
}
hotInstance.getSettings().colWidths[0] = hotInstance.getPlugin(‘autoColumnSize’).getColumnWidth(0);

with no luck :frowning_face: what is wrong am i doing? please help

Here is my code:

import React, { useEffect, useState } from 'react';
import Handsontable from 'handsontable';
import 'handsontable/dist/handsontable.full.css';
import { APICallsTerminalsJsonSix } from './APICalls'; 
import {APICallsTerminalsParaZero} from './APICalls';
import {Grid} from '@mui/material';
import ParameterInputFormDailog from './ParameterInputFormDailog';
import ParameterInputForm from './ParameterInputForm';


const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));


export default function FullFeaturedDemo() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);




  const fetchDataFromAPI = async (MainTableParamters) => {
    try {      
 
      const data = await APICallsTerminalsJsonSix( MainTableParamters);
  
      await delay(1000);  
      console.log(" incoming data:", data);
      const newData = data.map((row, index) => ({ ...row, id: index + 1 }));
      setData(newData);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching data:', error);
      setLoading(false);
    }
  };
  
  const fetchDataFromAPIMainTable = async () => {
    try {
      // const data = await APICallsTerminalsParaZero();
      const data =await APICallsTerminalsParaZero();
  
      await delay(1000);  
      console.log(" incoming data:", data);
      const newData = data.map((row, index) => ({ ...row, id: index + 1 }));
      setData(newData);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching data:', error);
      setLoading(false);
    }
  };


  useEffect(() => {
    fetchDataFromAPIMainTable(null, null,null,null,null,null);
  }, []);










  useEffect(() => {
    if (!loading) {


      const productNames = {
        '0187': ' [0187] Gasoline Regular Unleaded',
        '0289': ' [0289] Diesel Fuel Ultra Low Sulfur',
        '0290': ' [0290] Diesel Fuel Low Sulfur',
        '0391': ' [0391] Kerosene',
        '0393': ' [0393] Aviation Gasoline',
        '06': ' [06] Propane',
        '07': ' [07] Butane',
        '09': ' [09] Isobutane',
        '14': ' [14] Heavy Fuel Oil (HFO)',
        '15': ' [15] Light Fuel Oil (LFO)',
        '15CFI': ' [15CFI] Jet Fuel',
        '15HO': ' [15HO] Heating Oil',
        '18': ' [18] Lubricating Oils',
        '19': ' [19] Paraffin Wax',
        '1910': ' [1910] Liquefied Petroleum Gas (LPG)',
        '1910RFG': ' [1910RFG] Reformulated Gasoline',
        '1910RVP7.8': ' [1910RVP7.8] Reformulated Gasoline with Vapor Pressure of 7.8 psi',
        '1912': ' [1912] Asphalt',
        '1912RFG': ' [1912RFG] Reformulated Gasoline Blendstock',
        '1913': ' [1913] Gasoline Blendstock',
        '1991': ' [1991] Liquid Natural Gas (LNG)',
        '1992': ' [1992] Compressed Natural Gas (CNG)',
        '31': ' [31] Bitumen',
        '32': ' [32] Tar',
        '33/GALLON': ' [33/GALLON] Fuel Oil (per Gallon)',
        '41': ' [41] Benzene',
        '42': ' [42] Toluene',
        '85': ' [85] Xylene',
        '9402': ' [9402] Ethanol',
        '9405': ' [9405] Methanol',
        '9410': ' [9410] Acetone',
        '9411': ' [9411] Formaldehyde',
        '9414': ' [9414] Ethylbenzene',
        '9420': ' [9420] Cumene',
        '9499': ' [9499] Other Aromatic Solvents',
        '9702': ' [9702] Polyethylene',
        '9705': ' [9705] Polypropylene',
        '9711': ' [9711] Polyvinyl Chloride (PVC)',
        '9714': ' [9714] Polystyrene',
        '9720': ' [9720] Glycols',
        'CB0550/DRUM 55 GAL': 'Crude Oil (per 55 Gallon Drum)',
        'DEF-BLUE-275/TOTE 275 GA': 'Diesel Exhaust Fluid - Blue (per 275 Gallon Tote)',
        'DEF-BLUE-330/TOTE 330 GA': 'Diesel Exhaust Fluid - Blue (per 330 Gallon Tote)',
        'DEF-CB-275/TOTE 275 GAL': 'Diesel Exhaust Fluid - Clear (per 275 Gallon Tote)',
        'DEF-OW-00/GALLON': 'Diesel Exhaust Fluid - Other (per Gallon)',
        'DEF-OW-55/DRUM 55 GAL': 'Diesel Exhaust Fluid - Other (per 55 Gallon Drum)',
        'DEF000/GALLON': 'Diesel Exhaust Fluid (per Gallon)',
      };


      const products = Array.from(new Set(data.map((row) => row.Product)));

      const productColumns = products.map((product) => ({
        data: product,
        title: productNames[product] || product,
        width: 150,
      }));


      

      const pivotData = () => {
        const pivotedRows = {};
        let idCounter = 1;
      
        data.forEach((row) => {
          const { TerminalFullName, Product, ProductPrice, SupplyPtSupplierSupplyPtDescr, PurchRackPriceEffDtTm } = row;
          const key = `${TerminalFullName}-${SupplyPtSupplierSupplyPtDescr}`;
      
          if (!pivotedRows[key]) {
            pivotedRows[key] = {
              id: idCounter++,
              TerminalFullName,
              SupplyPtSupplierSupplyPtDescr,
              PurchRackPriceEffDtTm,
            };
          }
      
          pivotedRows[key][Product] = ProductPrice;
        });
      
        return Object.values(pivotedRows);
      };

      const columns = [
        { data: 'TerminalFullName', title: 'Terminal Name', width: 200 },
        { data: 'SupplyPtSupplierSupplyPtDescr', title: 'Supplier', width: 200 },
        { data: 'PurchRackPriceEffDtTm', title: 'Effective Date', width: 200 },
        ...productColumns,
      ];


      const hotElement = document.getElementById('hot');
      const hotInstance = new Handsontable(hotElement, {
        data: pivotData(),
        colHeaders: columns.map(col => col.title),
        columns: columns.map(col => ({ data: col.data, width: col.width })),
        autoColumnSize: true,
        autoRowSize: true,  
     
        
        rowHeaders: true,
        columnSorting: true,
        filters: true,
        dropdownMenu: true,
        // height: 'auto',
        // licenseKey: 'non-commercial-and-evaluation',
        // colWidths: [800, 400, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null],
        // colWidths: [900, 900, 400, 900, 50],

 
        height: 600, 
        // readOnly: true,
        // columnHeaderHeight: 40, 
        // rowHeaderWidth: 150, 
        // manualColumnResize: true, 
        // manualRowResize: true, 
        // manualColumnMove: true, 
        // manualRowMove: true, 
        // contextMenu: true, 
      //   afterRender: function() {
      //     this.updateSettings({ autoColumnSize: true });
      // }

     
     
});
      // hotInstance.getSettings().colWidths[0] = hotInstance.getPlugin('autoColumnSize').getColumnWidth(0);
 
      return () => {
        hotInstance.destroy();
      };
    }
  }, [loading, data]);  

  return (
    <>
      {loading ? (
        <div>Loading...</div>
      ) : (
        <div>
       
          <Grid item xs={12} >
              <Grid container spacing={1} justify="space-between">
              <Grid item xs={12} style={{ marginBottom: "20px" }}> 
                  <ParameterInputForm onSubmit={fetchDataFromAPI} />
                </Grid>
               


                <Grid item> 
                <Grid item xs={12} style={{ marginBottom: "20px" }}> 
                <ParameterInputFormDailog onSubmit={fetchDataFromAPI} />
                </Grid>

                </Grid>
              </Grid>
          </Grid>



        <div id="hot" style={{ marginTop: '20px', width: '100%' }} />
        </div>

      )}
    </>
  );
}

Thank you in advance!

While we are on this Thread.

  1. How would I get ride of the extra spaces when there is less columns

Hi @noajm

By default, the column widths adjust to the text inside (if it comes from the data, not from the cell renderer).

Now, to get an effect of columns being expanded to fill the container, you’d need to add stretchH option, possibly set to all cause that stretches all of the columns.

If you want, we can test it together. But I would need some help with the demo https://stackblitz.com/edit/vitejs-vite-9tgasd?file=src%2FApp.jsx,package.json,src%2Fmain.jsx,src%2FApp.css,src%2Findex.css&terminal=dev it doesn’t look the same as yours.

@aleksandra_budnik

Thank you that worked!

For StretchH hmmmm I am fan of it and not fan of it lol

but I think the following work nice as does not look to stretchy when it has too many cols

    const visibleCols = hotInstance.countCols();
    if (visibleCols < 8) {
      hotInstance.updateSettings({
        stretchH: 'all',
      });
    }

This ticket I think can be closed and thank you for creating the application instance :rose:

@noajm

I take back what I said about visibleCols.

It looks ugly and can be confusing for users when switching between expanded and not expanded views. It’s a headache! :sweat_smile:

Maybe there’s an option to do an A/B test with users? :slight_smile: That will help you decide. Or, you can always add a switch for those users who prefer the stretched table.

I like that, having a toggle option for stretched table.

You always think out of the box. Thanks!

This can be closed for now, thank you!

1 Like

I’m always happy to help :slight_smile: