Colin Sygiel
Colin Sygiel

Reputation: 947

In React, how can I use HOC (High Order Component) to create several components out of a generic component?

I have created a generic component to be used as a wrapper for other components to be used as labels. Here is my generic component:

const Label = ({ data, attribute, style, link }) => {
  if (link) {
    return (
      <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
    );
  }
  return (
    <div style={style}>{data ? `${data[attribute]}` : ''}</div>
  );
};

I want to use this as my generic component for rendering different label components such as:

const CityLabel = ({ data }) => (
  <div>{data ? `${data.city}` : ''}</div>
  )

and

const UserLabel = ({ user }) => (
  <div>{user ? `${user.firstName} ${user.lastName}` : ''}</div>
  )

etc...

How can I use a HOC to do this?

Upvotes: 0

Views: 260

Answers (1)

hazardous
hazardous

Reputation: 10837

This example assumes UserLabel only renders name instead of firstName & lastName as your Label component cannot handle two attributes.

const Label = ..., 
makeLabel = (
    (Label) => (mapLabelProps) => (props) => 
        <Label {...mapLabelProps(props)} />
)(Label),
CityLabel = makeLabel(({data, style, link}) => ({
    data,
    attribute: 'city',
    style,
    link
})),
UserLabel = makeLabel(({user, style, link}) => ({
    data: user,
    attribute: 'name',
    style,
    link
}));

render(){
    return (
        <div>
            <CityLabel data={{city:"NYC"}} />
            <UserLabel user={{name:"obiwan"}} />
        </div>
    )
}

Upvotes: 1

Related Questions