Ervin Enriquez
Ervin Enriquez

Reputation: 57

Returning a function vs setting a const equal to a function in React

I'm relatively new to React and was wondering why I'm getting a Functions are not valid as a React child. This may happen if you return a Component instead of from render error.

In my code there is an existing:

const SomeConst = SomeFunctionThatReturnsAComponent();

Now I am trying to update that const to have some logic before calling the function like so:

const SomeConst = (props) => {
   //Some logic
   return (SomeFunctionThatReturnsAComponent()());
}

Here is SomeFunctionThatReturnsAComponent():

const Template = component => (props) => {
   const ReturnThisComponent = props => <Component component={component}, {props} />

   return ReturnThisComponent;
}

The usage of SomeConst remains the same as the original implementation:

const SomeComponent = (props) => {

   return (<SomeConst prop1="foo"/>)
}

I am wondering why this is not functionally the same thing and why I am getting this error. I have not been able to find a post that gets this error with the way I have it implemented. They are different implementations that arrive at this same error so they were not that much of a help to me.

If there is another post, I would kindly ask to link me to it and I will quickly remove this post and link it to the other post for future people.

Please let me know if I can clarify anything, I have tried to create this post as a repex.

Upvotes: 1

Views: 84

Answers (1)

kind user
kind user

Reputation: 41893

tl;dr - you are missing one function call.

SomeFunctionThatReturnsAComponent()();

what does each parentheses do?

The first parens are calling the first function, that returns a function that returns ReturnThisComponent. If you call this function (Template) only once, you will still return a function (props) => { ... };

const Template = component => (props) => {
  const ReturnThisComponent = props => <Component component={component}, {props} />

  return ReturnThisComponent;
}

So either - call the function twice, or - remove the second curried function (props) => (and I think this is what you wanted to achieve). So it will look like:

const Template = (component) => {
  const Component = component;

  const ReturnThisComponent = (props) => <Component {...props} />;

  return ReturnThisComponent;
}

Upvotes: 1

Related Questions