How to Call a Function inside a Render in React/Jsx

254,534

Solution 1

To call the function you have to add ()

{this.renderIcon()}   

Solution 2

class App extends React.Component {
  
  buttonClick(){
    console.log("came here")
    
  }
  
  subComponent() {
    return (<div>Hello World</div>);
  }
  
  render() {
    return ( 
      <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
          {this.subComponent()}
       </div>
     )
  }
  


}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

Solution 3

The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,

First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.

So we use that variable to invoke the function by adding parentheses () at the end.

One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().

Share:
254,534

Related videos on Youtube

lost9123193
Author by

lost9123193

Learning

Updated on July 05, 2022

Comments

  • lost9123193
    lost9123193 almost 2 years

    I want to call a function inside some embedded html. I tried the following but the function isn't called. Would this be the incorrect way of calling a function inside a render method?

    import React, { Component, PropTypes } from 'react';
    
    export default class PatientTable extends Component {
          constructor(props) {
            super(props);
            this.state = { 
             checking:false
          };
            this.renderIcon = this.renderIcon.bind(this);
      }
    
      renderIcon(){
        console.log("came here")
        return(
          <div>Function called</div>
        )
      }
    
      render() {
    
       return (
           <div className="patient-container">
    
           {this.renderIcon}      
    
          </div>
       );
     }
    }
    
  • arora
    arora about 7 years
    it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this). is this correct? someone has written it below.
  • Pranav Singh
    Pranav Singh over 5 years
    this seems better since when you need to pass event or parameters this works
  • orion elenzil
    orion elenzil over 4 years
    super minor note, for those using coffeescript, this would be {@renderIcon()}
  • Galupuf
    Galupuf over 4 years
    I would recommend NOT doing this. 1.) renderIcon is/should be a component. {this.renderIcon()} is not how you use components in React. 2.) Your render is the source of truth for what your component is rendering. Abstracting that adds additional complexity.
  • dknaack
    dknaack over 4 years
    Besides the fact that this answers is 3 years old I am not sure if I agree. IMHO I abstract this kind of things in separate components only if it is used in more than component. Some does it only after 3 reuses. THX for your comment on this old answer. Really appreciate it. All the best.
  • dknaack
    dknaack over 4 years
    BTW. The uppercase is due to my correction chrome extension.
  • Galupuf
    Galupuf over 4 years
    You mention not abstracting to a component unless you need to reuse it. What's the benefit here of abstracting this to a method? React components are just functions so why do it this way? I've mentioned a couple reasons why I wouldn't do this. What are the reasons to do this?
  • Galupuf
    Galupuf over 4 years
    For those of you interested in why this is generally and objectively a bad practice, please see this: kentcdodds.com/blog/dont-call-a-react-function-component It's worth mentioning that this answer is correct and does a great job of answering the posted question. I just think it's worth the effort of teaching people that if they find themselves writing code like this there is a reason NOT to do it.
  • Tomasz Waszczyk
    Tomasz Waszczyk about 4 years
    @dknaack How to call the function only once?
  • dknaack
    dknaack about 4 years
    @TomaszWaszczyk e.g using the react hook useEffect.
  • jaycee
    jaycee over 3 years
    @Galupuf One reason that can justify doing it IMO is that for example you have a condition and dont want to use a nested ternary: myConditionalRender(){ if(loading) return <Loader /> if(error) return <Error /> return <MyComponent /> } and render(){ <div> ...more stuff ... {myConditionalRenderer()} }
  • Galupuf
    Galupuf over 3 years
    Why not just put that condition in a component? It achieves the same things without any of the bad side effects