what if we accidently don't use '()' after calling the method

Viewed 77

What if we forget put the parentheses after calling function, like when we have

renderContent(){}

and we want to call it in a div

<div>{this.renderContent()}</div>

what if we forget write ()?
it shows no error and shows nothing in the screen
and when we put () after calling, it shows if I got a problem like this how can I know where I didn't put ()
if you need more information please let me know

2 Answers

All that will happen in this specific case is it will print the function's code. So for example if you have a function like

renderContent = () => {
   console.log("hi");
   return <p>Hello world</p>;
}

Then using it without the parenthesis will just print the contents of the function, whereas using the parenthesis will print the JSX for the p tag <div>{this.renderContent()}</div> will return <p>Hello world</p> within the div, whereas without the parenthesis, it will just print

() => {
   console.log("hi");
   return <p>Hello world</p>;
}

which is the function's contents

import React, { Component } from 'react';

class Content extends Component {
    renderContent = () => <h1>Hi</h1>
    render() {
        return (
            <div>{this.renderContent()}</div>
        )
    }
}

export default Content;

This will show "Hi" in the screen. But if you've deleted () from this.renderContent():

import React, { Component } from 'react';

class Content extends Component {
    renderContent = () => <h1>Hi</h1>
    render() {
        return (
            <div>{this.renderContent}</div>
        )
    }
}

export default Content;

It's showing nothing on the screen, and you would have an error in the console:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
Because it supposed to return the structure of the function (if in vanilla javascript), but this is not allowed in React js

Related