Alessandro
Alessandro

Reputation: 4472

React-table, how to indenting column

I've a rest service that returns a json string like the following:

[
{"id":1,"position":100,"parent":null,"description":"Row 1"}, 
{"id":2,"position":110,"parent":100,"description":"Row 1.1"},
{"id":3,"position":200,"parent":null,"description":"Row 2"},
{"id":4,"position":210,"parent":200,"description":"Row 2.1"},
{"id":4,"position":211,"parent":210,"description":"Row 2.1.1"},
// Etc...
]

I'd like to show those data in a react-table indenting the description like a treeview in according with the column position.

I've already shown the data sorted by position, but I can't "override" the column description.

const columns = [{
        Header: 'id',
        accessor: 'id',
        show: false
    }, {
        Header: 'Description',
        accessor: 'description'  //<-- HERE I'D LIKE TO ADD A KIND OF FORMULA
    }];

<ReactTable
    data={this.state.skills}
    columns={columns}
    defaultPageSize={25}
    showPagination={true}
    defaultSorted={[
        {
            id: "position"
        }
    ]}
/>

How can I trasform a column in a react-table?

My goal is something like (in "pseudo-code"):

const columns = [{
        Header: 'id',
        accessor: 'id',
        show: false
    }, {
        Header: 'Description',
        accessor: {
            let spaces = row["description"].indexOf("0");
            if(spaces>-1){
               return " ".repeat(spaces) + row["description"];
            } else {
               return row["description"];
            }
        }
    }];

Thanks

Upvotes: 1

Views: 1316

Answers (1)

dmitri7
dmitri7

Reputation: 193

Use cell property:

const columns = [{
    Header: 'id',
    accessor: 'id',
    show: false
}, {
    Header: 'Description',
    Cell: props => {
        let spaces = props.original.description.indexOf("0");
        if(spaces>-1){
           return <span>{" ".repeat(spaces) + props.original.description}</span>
        } else {
           return <span>{props.original.description}</span>
        }
    }
}];

Upvotes: 2

Related Questions