Search code examples
javascriptreactjsreact-bootstrap-table

Invariant Violation error when returning a Link as dataFormatter in react


In the table Column title I want to return links which navigate to edit mode of each of these titles. I'm using react-bootstrap-table and I created a custom data formatter in the constructor of my component

class Grid extends Component {
  constructor(props) {
    super(props);
    this.anchorFormatter = (cell, row, slug) => {
      let link = "/"+slug;
      return (
        <Link to={link}>
          {cell}
        </Link>
      )
  }

I then call this data formatted in the table

<TableHeaderColumn isKey dataField="title" dataSort dataFormat={ this.anchorFormatter }>Title</TableHeaderColumn>

This is get this error

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `TableBody`.

The second part is how do I pass value of slug to the data formatter? I get data like this from the get request API Call

{
  "title": "Experiments in DataOps",
  "status": true,
  "publish_date": "2020-01-29",
  "slug": "experiments-in-dataops"
},

Solution

  • Another approach is to create a class or function and then use it as a component, here I create the component

    class BlogAnchor extends Component {
        constructor(props) {
            super(props);
        }
    
        render() {
            return (
                <Link to={this.props.link}>&nbsp;{this.props.linkText}&nbsp;</Link>
            );
        }
    }
    

    then in the Grid class I have a function

    anchorFormatter(cell, row) {
        let link = "blogs/" + row.slug;
        return <BlogAnchor link={link} linkText={cell} />;
    }
    

    which is also registered in the constructor of Grid class

    this.anchorFormatter = this.anchorFormatter.bind(this);
    

    And the table column refers to this this function

    <TableHeaderColumn isKey dataField="title" dataSort dataFormat {this.anchorFormatter}>Title</TableHeaderColumn>