g3blv g3blv - 2 months ago 17
React JSX Question

Access props outside class

I'm using

react-bootstrap-table
with
cellEdit
enabled. It is possible to use a callback function in
react-bootstrap-table
after the cell has been edited. I've named the callback function
onAfterSaveCell
. The updated row in table will be saved to a variable called
row
. I would like to send
row
to an action creator called
pushData
that accepts
row
as an input. My code looks like this.

function onAfterSaveCell(row, cellName, cellValue){
this.props.pushData(row);
}

const cellEditProp = {
mode: "click",
blurToSave: true,
afterSaveCell: onAfterSaveCell
};

class Feature extends Component {
componentWillMount() {
this.props.fetchMessage();
}

render() {
if (!this.props.message) return null

return (
<div>
<BootstrapTable
data={this.props.message}
cellEdit={cellEditProp}
>
<TableHeaderColumn dataField="ccyCode" isKey={true} dataSort={true}>Valutakod</TableHeaderColumn>......


When I run the code I the error
Uncaught TypeError: Cannot read property 'props' of undefined
. Which I think is due to that
props
is not available outside the
class Feature
. I've tried to move in the
onAfterSaveCell
function and
cellEditProp
in to
class Feature
but this give me a compilation error. How can I make
props
accessible outside the
class Feature
or should this be solved in some other way?

Answer

You are right, you cannot use the this keyword outside the class. So the obvious answer is to define your callback-function inside the class. I think the reason you got a compilation error is due to a syntax error, since this should work just fine:

class Feature extends Component {
  constructor(props, context) {
    super(props, context);
    this.onAfterSaveCell = this.onAfterSaveCell.bind(this); // important!
  }

  componentWillMount() {
    this.props.fetchMessage();
  }

  onAfterSaveCell(row, cellName, cellValue) {
    this.props.pushData(row);
  }



  render() {
    if (!this.props.message) return null

    return (
    <div>
      <BootstrapTable
              data={this.props.message}
              cellEdit={{
                mode: "click",
                blurToSave: true,
                afterSaveCell: this.onAfterSaveCell
                }}
              >
        <TableHeaderColumn dataField="ccyCode" isKey={true} dataSort={true}>Valutakod</TableHeaderColumn>......