dc.js

how to format or customize the section label of dc.js dataTable


when using a dc.dataTable with sections, the "section" method receives a callback to return the value to use as key for the sections. This value is used for grouping the data into sections, and, if you enable to display section headers, is then used as label for each section's table.

My question is, how can I customize that label, so it is different for the value used internally by the section method?

my problem is that I am using a date as section key, that needs to be formated into specific locale (month-day-year) but that causes the sorting of the sections to be incorrect (sorts alphabetically). If I pass a Number like YYYYMMDD the sorting of sections is OK, but then the label is not in the right format.

There is some way to format the section key before it is being used to print the label of each section?

Note: sortBy doesn't seems to have effect over the ordering of the sections.


Solution

  • Good observations here!

    1. There is no built-in way to format the section headers.
    2. There is no independent way to sort the sections - it uses the same .order() function as is used for the data. Yes... it's weird to assume that the section headers will even have the same type as the field retrieved by sortBy for the rows.

    Due to observation 2, I think you are correct that you will need to provide a group key that sorts in lexicographical order.

    But you can use a pretransition hook to change the labels after the chart is rendered and before it is displayed:

    const parseGroupKey = d3.timeParse('%Y/%m')
    const sectionFormat = d3.timeFormat('%B %Y');
    
    nasdaqTable.on('pretransition', table => {
      table.selectAll('tr.dc-table-section td')
        .html(d => {
          const date = parseGroupKey(d.key);
          return sectionFormat(date);
        })
    });
    

    This hook, tested with the stock example data/code,

    1. selects all the section header cells
    2. reads the data that is bound to them, which is in {key,value} format
    3. parses the key, which is the string previously generated by the .section() accessor
    4. formats it with a different time formatter

    table with custom section formatting

    Example fiddle.

    It would be nice to fix both of the limitations you have identified. Contributions are welcome!