basse
basse

Reputation: 1339

Pass props to higher-order stateless functional React component

I would like to create a function that returns different versions of a stateless functional React component. My goal is to refactor this working code:

import React from 'react';
import { Icon } from 'react-icons-kit';
import { socialFacebook, socialTwitter } from 'react-icons-kit/metrize';


export const FacebookIcon = ({ className, size }) => (
  <Icon
    icon={socialFacebook}
    size={size}
    className={className}
  />
);

export const TwitterIcon = ({ className, size }) => (
  <Icon
    icon={socialTwitter}
    size={size}
    className={className}
  />
);

Into something like this:

import React from 'react';
import { Icon } from 'react-icons-kit';
import { socialFacebook, socialTwitter } from 'react-icons-kit/metrize';


const ProtoIcon = ({ icon }) => ({ className, icon, size }) => (
  <Icon
    className={className}
    icon={icon}
    size={size}
  />
);

export const FacebookIcon = ProtoIcon(socialFacebook);
export const TwitterIcon = ProtoIcon(socialTwitter);

However, the above fails and the problem seems to be that icon isn't passed on to the returned function. What is the best way to solve this? Reading the React manual on HOC's, I suppose this could be done by returning a class that extends React.component but I really like the form that I've tried above. Is it possible to achieve what I'm trying to do in a functional-ish way?

Thanks!

EDIT1: To clarify, my final API would be (<FacebookIcon size={32} className="some-class">).

Upvotes: 0

Views: 85

Answers (1)

Win
Win

Reputation: 5584

You're very close. FacebookIcon and TwitterIcon need to be converted to stateless components so that we can pass props into it. You've just created a variable reference to the ProtoIcon component that doesn't, unfortunately, return the JSX when used.

import React from "react";
import ReactDOM from "react-dom";
import { Icon } from 'react-icons-kit';
import { socialFacebook, socialTwitter } from 'react-icons-kit/metrize';

const ProtoIcon = (icon, props) => (
  <Icon icon={icon} {...props} />
);

export const FacebookIcon = (props) => ProtoIcon(socialFacebook, props);
export const TwitterIcon = (props) => ProtoIcon(socialTwitter, props);

function App() {
  return (
    <div className="App">
      <FacebookIcon size={32} className="some-class" />
      <TwitterIcon size={32} className="some-class"/>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 2

Related Questions