How to conditionally render the button in react-bootstrap-table ? (The button for each row)

纵饮孤独 提交于 2019-12-01 13:25:36
iamsaksham

Your logic seems correct but implementation is a bit wrong.

cellButton(cell, row, enumObject, rowIndex) {
  let theButton;
  let groupExistsInDatabase = false;
  for(var group in this.state.jsonFromDatabase){
    if (this.state.jsonFromDatabase[group].id === row.id){
      // make groupExistsInDatabase true if the group is found in the database
      groupExistsInDatabase = true;
      break;
    }
  }

  if(groupExistsInDatabase === true) {
    theButton = <button style={{ backgroundColor: "red" }} type="button" onClick={() => this.onClickGroupToUpdate(cell, row, rowIndex)}>
                  Update the group
                </button>
  } else {
    theButton = <button style={{ backgroundColor: "blue" }} type="button" onClick={() => this.onClickGroupSelected(cell, row, rowIndex)}>
                  Process the group
                </button>
  }
  return theButton;
}

This solution should work. Let me know if there are some modifications.

Issue is you are returning one one button from cell formatter function.

Use this:

cellButton(cell, row, enumObject, rowIndex) {
    let uiItems = [];
    for(var group in this.state.jsonFromDatabase){
        if (this.state.jsonFromDatabase[group].id !== row.id){
            uiItems.push(<button style={{ backgroundColor: "blue"}}
                            type="button"
                            onClick={() => this.onClickGroupSelected(cell, row, rowIndex)}>
                                Process the group
                        </button>)
        }else{
                uiItems.push(<button style={{ backgroundColor: "red" }}
                                type="button"
                                onClick={() => this.onClickGroupToUpdate(cell, row, rowIndex)}>
                                   Update the group
                            </button>)
        }
    }
    return uiItems;
}

or use map, like this:

cellButton(cell, row, enumObject, rowIndex) {
    return this.state.jsonFromDatabase.map((group, i) => {
        if (group.id !== row.id){
            return  <button style={{ backgroundColor: "blue"}}
                        type="button"
                        onClick={() => this.onClickGroupSelected(cell, row, rowIndex)}>
                            Process the group
                    </button>
        }else{
            return  <button style={{ backgroundColor: "red" }}
                        type="button"
                         onClick={() => this.onClickGroupToUpdate(cell, row, rowIndex)}>
                            Update the group
                    </button>
        }
    })
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!