user2279235
user2279235

Reputation:

React: Is it ok to pass a component to another component through the props?

If I have a component, for example <Foo /> that renders something like this:

<div>
   <Bar />
   {/* ... */}
</div>

Would it be possible to pass Bar as a property of Foo? <Foo Bar={Bar}/>. So I can reference Bar during the render of Foo:

render() {
  const Bar = this.props.Bar;
  return (
    <div>
      <Bar />
      {/* ... */}
    </div>
  );
}

I don't know if this would be a good idea to be honest, just checking to see if somebody knows better than me.

The reason I would like to do something like this is because I want to test a component and was thinking on how to inject fake dependencies into the component. For a project I was thinking on using Preact, which does not work with shallow render, therefore I was thinking on perhaps doing some kind of dependency injection.

Passing through the components that the component uses would allow me to fake them during testing, passing mocks.

Is this a good idea? Or not really the way to go?...

Upvotes: 0

Views: 738

Answers (1)

F. Kauder
F. Kauder

Reputation: 889

I don't know why it could be a bad Idea.

When you build a React component, you're building a Javascript object with some syntax (JSX) which will be translated to plain Javascript. So passing a React component is like passing any Javascript object.

For information, that's the way react-router use to pass component in Route.

Upvotes: 1

Related Questions