Search code examples
reactjsonclickthisreact-bootstrap-table

I am trying to use rowEvents to trigger an action in react-bootstrap-table-2 but 'this' in the onClick is undefined. Any ideas?


Here is the codeblock:

const expandRow = {
    renderer: row => (
        <div>
            <BootstrapTable
                keyField='id'
                data={ row.data }
                columns={ columns1 }
            />
        </div>
    )
};

export default class MyPage extends Component {
    constructor(props, context) {
        super(props, context);
    }

    componentDidMount() {
        this.props.actions.fetchData().  // fetches in this.props.data
    }

    rowEvents = {
        onClick: (e, row, rowIndex) => {
            this.props.actions.fetchHistory(row.Id).   /* this is undefined */
        }
    }

    render() {

        return (
            <BootstrapTable
                keyField='Id'
                data={ this.props.data }
                columns={ columns }
                striped
                rowEvents={ this.rowEvents }
                expandRow={ expandRow }
            />
        )
    }
}

What I am trying to do is for each row clicked, I want to fetch data by triggering an action. I might be wrong about understanding the context of 'this' here. Any ideas?


Solution

  • I was able to figure out a way to fix the 'this' context issue. Implementing the rowEvents in a slightly different way as below. I am still not quite sure why I ran into such a context issue.

    let rowEvents = () => {
        return{
        onClick: rowOnClick
        }
    }
    async function rowOnClick(e, row, rowIndex) {
        await this.props.actions.fetchLogHistory(row.orchestratorId)
    }
    
    and bind rowOnClick to this in the constructor:
    this.rowOnClick = this.rowOnClick.bind(this)
    

    However, although I used async/await to trigger the action, I ran into another issue where the expanded row (inner) bootstrap table loaded before the action got reduced and it had no data in the props. What I am attempting now is to use another Component rendered in expanded row, and in it, I'll have the inner bootstrap table, whose componenDidMount will fetch the data.