user5992977
user5992977

Reputation:

React how to invoke a prop

I'm trying to invoke a method on the component props before the page load. For testing I've created a button to invoke the method , but this is not what I desire , and I don't know how to change it so it will be called instantly when you reach this path .

My current code :

class BrokersList extends React.Component {
  getTableData = () => {
    this.props.getBrokerDetails()
  }

  render () {
    return (
      <Paper className={this.props.classes.root}>
        <button 
                variant="outlined" 
                color="primary" 
                onClick={this.getTableData}></button>

          {this.props.details.length > 0 && <Table {...this.props}/>}
      </Paper>

    )
  }
}

I thought about calling the getTableData via the render method, but render should be pure so it didn't work . (Table component is being populated from the state that is being updated by this method)

Upvotes: 0

Views: 190

Answers (3)

Chaim Friedman
Chaim Friedman

Reputation: 6253

For this you can use the componentDidMount life cycle method.

Here is example code of what may work for you.

class BrokersList extends React.Component {
  componentDidMount() {
    this.props.getBrokerDetails()
  }

  render () {
    return (
      <Paper className={this.props.classes.root}>
          {this.props.details.length > 0 && <Table {...this.props}/>}
      </Paper>

    )
  }
}

Now your call to getBrokerDetails will fire right after the first render of this component. See here for more details on this life cycle method.

Upvotes: 3

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

What's wrong with this?

class BrokersList extends React.Component {
  render () {
    // get method props
    const {getBrokerDetails} = this.props
    return (
      <Paper className={this.props.classes.root}>
        <button 
                variant="outlined" 
                color="primary" 
                onClick={getBrokerDetails}></button>
                {/* call the method ^^ */}

          {this.props.details.length > 0 && <Table {...this.props}/>}
      </Paper>

    )
  }
}

Upvotes: 0

jcubic
jcubic

Reputation: 66478

If you pass method to handler as is that use this it will be window object or undefined if used in strict mode:

class BrokersList extends React.Component {
  getTableData = () => {
    this.props.getBrokerDetails()
  }

  render () {
    return (
      <Paper className={this.props.classes.root}>
        <button 
                variant="outlined" 
                color="primary" 
                onClick={() => this.getTableData()}></button>

          {this.props.details.length > 0 && <Table {...this.props}/>}
      </Paper>

    )
  }
}

or using onClick={this.getTableData.bind(this)}

Upvotes: 0

Related Questions