6

I am using react-table package and it's table.

In the table column props I have submitted object as it formats properly.

    Header: 'Charter',
      columns: [
          {
              Header: 'Title',
              accessor: 'charter_title',
              style: {
                  textAlign: 'center'
              }
          }
      ]
    }

What I want to do is to format this column value as currency

i.e. 10000.53 would be come 10,000.53

i.e. 1230000.123 would be come 1,230,000.123

Does react-table give you opportunity to do this kind of formatting?

Community
  • 1
  • 1
Lululu
  • 675
  • 3
  • 9
  • 21
  • Yes, you can do it of course. Documentation has all you need for this. – dfsq Feb 09 '18 at 10:59
  • Also you can do it with javascript, check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString – arikanmstf Feb 09 '18 at 11:02
  • @dfsq Yeah, but [documentation](https://github.com/react-tools/react-table/blob/master/src/defaultProps.js) seems that it ain't got field for column formatting, or I am missing something? – Lululu Feb 09 '18 at 11:12
  • I think you need `accessor`. – dfsq Feb 09 '18 at 11:44
  • @dfsq could you kindly give an example how to do it. Am not able to find it in the docs. – Phares Jan 09 '19 at 15:07

2 Answers2

17

I have found out that Cell props define what the output of each cell will be. Here's some working code. You can provide the custom function to format each cell's value as you like.

Header: 'Charter',
       columns: [
          {
              Header: 'Title',
              accessor: 'charter_title',
              style: {
                  textAlign: 'center'
              },
              // provide custom function to format props 
              Cell: props => <div> toCurrency(props.value) </div>
          }
      ]
}

My custom function is:

function toCurrency(numberString) {
    let number = parseFloat(numberString);
    return number.toLocaleString('USD');
}
Kevin
  • 16,549
  • 8
  • 60
  • 74
Lululu
  • 675
  • 3
  • 9
  • 21
  • 3
    Good answer. the syntax needs a little tweaking. I used Cell: props => {this.toCurrency(props.value)} – joedotnot Dec 11 '18 at 00:56
4
Header: 'Charter',
   columns: [
      {
          Header: 'Title',
          accessor: 'charter_title',
          style: {
              textAlign: 'center'
          },
          Cell: props => new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'USD' }).format(props.value)
      }
  ]

}

Phares
  • 1,008
  • 13
  • 20