简体   繁体   中英

- AJAX DataTables - Adding a condition in 'columns' (render) which returns a button (Link) of React-Router is not working - ReactJS -

I have one DataTable which is:

export default class TablaMisIncidencias extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        $('#idTablaMisIncidencias').DataTable({
            responsive: true,
            "paging": true,
            "ordering": true,
            select: false,
            "lengthMenu": [[5, 10, 25, -1], [5, 10, 25, "Todas"]],
            columnDefs: [
                { 
                    responsivePriority: 1, 
                    targets: 0 
                },
                { 
                    responsivePriority: 2, 
                    targets: 1 
                },
                { 
                    responsivePriority: 3, 
                    targets: 5 
                },
                { 
                    responsivePriority: 4, 
                    targets: 2 
                },
                { 
                    responsivePriority: 5, 
                    targets: 3 
                },
                { 
                    responsivePriority: 6, 
                    targets: 4 
                }
            ],
            "ajax": {
                "url": "https://jsonplaceholder.typicode.com/comments",
                "dataSrc": ""
            },
            "columns": [
                { "data": "postId" },
                { "data": "id" },
                { "data": "name" },
                { "data": "name" },
                { "data": "body" },
                { "data": "body",
                    sortable: false,
                    //HERE IS THE ERROR
                    "render": function ( data, type, full, meta ) {
                        //console.log(full)
                        if (full.postId == 0) {
                            return (`
                                <Link to="eee" class='btn btn-info btn-xs' title="Editar"><span class="glyphicon glyphicon-edit"></span> Editar</Link>
                            `);
                        } else {
                            return (`
                                <a href="eee" class='btn btn-success btn-xs' title="Tramitada"><span class="glyphicon glyphicon-ok"></span> Tramitada</a>
                            `);
                        }
                    }
                },
            ]
        });
    }

If you see comment line: //HERE IS THE ERROR, on this function render I have two returs which are very similar. If postId == 0 it may returns one Link else may return one a . Both a and Link are the same. The unique difference is a is an HTML Tag and Link is a React-Router Tag. Well, when render returns a it is showed as a button (that is that I want, but I want that it happen too with Link); when render returns Link it is showed as text and the glyphicon, all separate, do not showed as button, and do not redirect neither. So, Why a is returned well and Link is not returned well? How could I solve this?

Thank you.

Datatables are tricky to work with react, the main reason is that you cannot render Components directly in the render prop of the columns, instead you have to use the createdCell property to actually render something with React.

The first thing that i see on your code is that you lack the data property, so you should add at least en ampty array [] . After that, you should have a componentDidUpdate to re-render the table in case you receive new props:

componentDidUpdate() {
    this.table.clear()
    this.table.rows.add(this.transform(this.props.data))
    this.table.draw()
}

This scenario will clear the table, then it will add data to it and will draw it again, notice that this.props.data is an array of elements.

Drawing a link in a column with React

The bad thing about Datatables is that it doesn't allow directly to draw a React Component. But instead it will give you access to the DOM reference inside a createdCell property when you initialize the table:

this.table = $(this.refs.main).DataTable({
  dom: '<"data-table-wrapper"tip>',
  data: [],
  columns,
  language: {
    info: 'Showing _START_-_END_ from _TOTAL_ entities',
    infoEmpty: 'No hay puntos',
    paginate: {
      next: 'Siguiente',
      previous: 'Anterior',
    },
  },
  headerCallback: (thead, data, start, end, display) =>
    ReactDOM.render(
      <input type="checkbox"
        onChange={() => this.props.toggleSelectAll()}
        checked={this.props.selected.length === this.props.data.length} />,
      thead.children[0]),
  columnDefs: [{
    targets: 5,
    createdCell: (td, cellData, rowData, row, col) =>
      ReactDOM.render(
        <a style={{ cursor: 'pointer' }}
          onClick={() => this.props.goto(cellData) }>
          <i className="icon-fontello-edit"></i>
        </a>, td),
  }],
})

Now, is very important to notice that <Link /> requires a context, so you could not add the to property because it will not understand the link definition, therefore what you need to do is handle that with a function, in this case we are rendering an anchor tag with an onClick handler, this handler is defined in the parent component as the following:

<Table
  goto={x => this.props.router.push(x)}
  data={this.props.table.data} />

the function will receive the url by the rendered field and will push it in the router. Now you have history and and links working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM