I've got some React code that is rendering content. Right now the code contains duplication, because the code should render one way if it contains call to action buttons, and another way if there are no call to action buttons in the props. I'm being asked to try and remove the duplication by converting the code to use a Higher Order Component (HOC), and I've not done this type of thing before in React. How would I go about reducing duplication by using a HOC?
const hasCtaLinks = ctaLinks && ctaLinks.length > 0 ? true : false;
The above code is what I wrote to determine whether or not the component should render using code block A or code block B. In the code below, leftText
refers to content passed in to the component.
Here is code block A:
{hasCtaLinks && (
<>
<LinkComponent
className="mds-d-block"
type="no-styles"
//...other props here
>
{leftText && (
<InnerComponent content={leftText || ""} />
)}
</LinkComponent>
<CtaComponent ctaLinks={ctaLinks} />
</>
)}
And here is code block B, which renders if there no CTAs in the content passed in to the component as a prop.
{!hasCtaLinks && leftText && (
<InnerComponent content={leftText || ""} />
)}
You can see that code block B is just a duplication of code that is in code block A.
I was able to solve this problem without using a HOC. Basically just propogating props.children in a conditional component, as follows:
const ConditionalLink = (props: LinkProps) => {
if (!props.href) {
return <>{props.children}</>;
}
return <Link {...props}>{props.children}</Link>;
};
And then replacing with instead in the code block A above.