Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda