Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Convert duplicative React code into a Higher Order Component w/o duplication?

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, leftTextrefers 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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda