Paul N
Paul N

Reputation: 613

Passing components as props? Compositional vs Higher Order Components

I'm creating some layout-level components for my React app. As I understand it there are two main design patterns I can utilize - compositional, and higher-order components.

Am I correct in thinking that I have to make use of props.children when I want to create a wrapper component in the compositional style?

And am I correct in thinking that if I want to, say, pass in two different components (as in the Higher-Order Components example below), I have to make use of the higher-order component style?

Compositional:

const CenteredColumn = props => (
  <div className="columns">
    <div className="column is-8 is-offset-2">{props.children}</div>
  </div>
);

Higher Order Component:

const withTwoColumns = ({ first, second }) => (
  <div className="columns">
    <div className="column">{first}</div>
    <div className="column">{second}</div>
  </div>
);

Upvotes: 1

Views: 677

Answers (3)

Emmanuel Yusufu
Emmanuel Yusufu

Reputation: 26

Yes you are right. The compositional style allows you to pass children to components ahead of time before they are aware that they have them. So we could do this:

Please see: https://facebook.github.io/react/docs/composition-vs-inheritance.html

So to the h1 and p tags, the div with a className of 'fancyborder' will cover/wrap/surround them.

Regarding HOCS, you are also correct. They are components they receive other component(s) as inputs and render component(s) as the output.

Pardon me not providing code. I used a touch device. Hope this helped.

Upvotes: 1

Andrew
Andrew

Reputation: 7545

Both work. From the way you're writing it, it's a coding style/hierarchical choice. There are anti-patterns for React, but this is not one of them.

Upvotes: 1

Cristopher E.
Cristopher E.

Reputation: 34

The way you should you set your layout is by dividing your workflow or proyect structure in presentatational ( Stateless) components and Container components.. The presentationals components will only receive props from their main components while the container components will contain the logic of the applications.

Upvotes: 0

Related Questions