0

I'm using this table component with radioboxes (Row selection(Single)) and I want to update the react state to the currently selected row.

A function called onRowSelect shows the row selected. To update the state to the row selected, I created a function called showRow(), which is called in onRowSelect. However, I keep getting a this.showRow() is not a function error.

I'm using showRow() outside the render function because I need to update the state with the currently chosen row.

class ChooseRowExample extends Component {
    constructor(props) {
      super(props);
      this.state =({
        chosenRow:""
      });
    this.showRow = this.showRow.bind(this);
  }

  showRow(row, isSelected){
      console.log(row);
      //update state here 
  }


  render() {

    var selectRowProp = {
      mode: "radio",
      clickToSelect: true,
      bgColor: "#A7EC57",
      onSelect: onRowSelect
    };

    function onRowSelect(row, isSelected){
      this.showRow(row, isSelected);
    }


  return (  
    <div>
        <BootstrapTable data={person} search={true} selectRow={selectRowProp}>
          <TableHeaderColumn dataField="id" isKey={true}>Client #</TableHeaderColumn>
          <TableHeaderColumn dataField="name">Company</TableHeaderColumn>
          <TableHeaderColumn dataField="contact_name">Client Name</TableHeaderColumn>
        </BootstrapTable>
      </div>
    )
  }
}
1
  • just move onRowSelect outside of render, with the other functions Commented Jun 22, 2016 at 1:26

1 Answer 1

1

The problem is that this within onRowSelect is not the instance of the component like you are expecting.

You can use an ES6 arrow function for a lexical this that will reference the component instance.

So instead of:

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: onRowSelect
};

function onRowSelect(row, isSelected){
  this.showRow(row, isSelected);
}

You should be able to do this:

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: (row, isSelected) => this.showRow(row, isSelected)
};

Or even simply the following as you have already bound showRow to the components context in the constructor :

var selectRowProp = {
  mode: "radio",
  clickToSelect: true,
  bgColor: "#A7EC57",
  onSelect: this.showRow
};

Here is a bit more of an expanation of how this works in JavaScript: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.