How to make it available inside the render function

This is my React component:

constructor(props) {
    super(props);

    this.state = {
    };
    this.showChart = this.showChart.bind(this)
}

showChart() {
    console.log('test')
}

render() {

    {this.showChart} //throws error that, this is undefined

    return () (
        {this.showChart} //prints test
    )
}

Now, if I want to call a function from render(), but outside return(), what should I do?

+4
source share
2 answers

The syntax of your component is incorrect in several places. thisavailable inside the render.

constructor(props) {
    super(props);

    this.state = {
    };
    this.showChart = this.showChart.bind(this)
}

showChart() {
    console.log('test')
}

render() {

  this.showChart() 

  return ( 
      <div>{this.showChart()}</div> 
  )

}

EDIT:

You can also work with arrow functions to bind specified functions to your component. By doing this, you do not need bindevery function. It looks a lot cleaner:

constructor(props) {
    super(props);

    this.state = {
    };
}

showChart = () => {
    console.log('test')
}

render() {

  this.showChart() 

  return ( 
      <div>{this.showChart()}</div> 
  )

}
+5
source

replace {this.showChart} with this.showChart () inside the render function. So your new code should be

render(){
 this.showChart();

 return(
      {this.showChart}      
);
}
0
source

Source: https://habr.com/ru/post/1684347/


All Articles