Search code examples
reactjsreact-table

How do I right justify data in react-table columns?


I have these columns defined in a bit of Node code to create columns in a react table:

const columns = [{
    Header: 'Regiom',
    accessor: 'region' // String-based value accessors!
  }, {
    Header: 'Division',
    accessor: 'division'
  }, {
    Header: 'File Client Id',
    accessor: 'facilityid'
  }, {
    Header: 'Meter #',
    accessor: 'meternumber'
  }, {
    Header: 'Service Address',
    accessor: 'serviceaddress'
  }, {
    Header: 'Service City',
    accessor: 'servicecity'
  }, {
    Header: 'Service Zip',
    accessor: 'servicezip'
  }, {
    Header: 'Account Number',
    accessor: 'accountnumber'
  }, {
    Header: 'Utility Provider',
    accessor: 'utilityprovider'
  }, {
    Header: 'Interval Start',
    accessor: 'intervalstart'
  }, {
    Header: 'Interval End',
    accessor: 'intervalend'
  }, {
    Header: 'kWh Usage',
    accessor: 'kwh_usage'
  }, {
    Header: 'kW Demand',
    accessor: 'kw_demand'
  }, {
    Header: 'Gas Unit of Measure',
    accessor: 'gas_uom'
  }, {
    Header: 'Gas Usage Amount',
    accessor: 'gas_usage_amount'
  }];

All I really want to do is leave the column headers centered but right justify the numbers - like, for example, the kWh Usage column. How do I do that? Is there a way to apply a style to a column within this? I tried the style: {text-align: right} and the code throws syntax errors...


Solution

  • You can do it via adding custom component in Header or Cell.

    const columns = [
      {
        Header: () => <div style={{ textAlign: "right" }}>Regiom</div>,
        accessor: "region",
        Cell: row => <div style={{ textAlign: "right" }}>{row.value}</div>
      },
      ...
      ...
    

    Here is the sample code for you.
    https://codesandbox.io/s/react-table-simple-table-eep26

    Hope this will work for you!