Home > Software design >  How to render FunctionComponent when passed as parameter?
How to render FunctionComponent when passed as parameter?

Time:04-07

I'm learning React (and typescript) and trying to render a FunctionComponent received from a function parameter, but nothing is being displayed. Here's my code:

    const myComponent: FunctionComponent = () => <h3>Hello World</h3>;

    const renderComponents = (theComponent: FunctionComponent) => {
        return (
            <div>
                {theComponent}
            </div>
        );
    };

    return renderComponents(myComponent);

However, if I simply return the raw HTML code:

 return <h3>Hello World</h3>;

It works fine.

How do I render a FunctionComponent from a function parameter?

CodePudding user response:

theComponent is the function itself. If you want it’s output you have to invoke it or JSX it:


const renderComponents = (theComponent: FunctionComponent) => {
  return (
    <div>
      {theComponent()}
    </div>
  );
};

You’d need to capitalize it for jsx usage:


const renderComponents = (TheComponent: FunctionComponent) => {
  return (
    <div>
      <TheComponent />
    </div>
  );
};

CodePudding user response:

Still a FunctionComponent is a JavaScript function, definitely you should run it to see it's result, in ReactJs there is a new syntax which its name is JSX, and it runs the FunctionComponent (JavaScript function) by other way:

const renderComponents = (theComponent: FunctionComponent) => {
        return (
            <div>
                <theComponent />
            </div>
        );
    };
  • Related