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

123
Visualizações
React PropTypes - OR

For this code:

const FirstComponentPropTypes = {
   foo: PropTypes.any,
};

const SecondComponentPropTypes = {
   bar: PropTypes.any,
};

...

function MyComponent({ foo, bar }) {
   if (foo) {
     return <FirstComponent foo={foo} />;
   } else if (bar) {
     return <SecondComponent bar={bar} />;
   }
   
   throw new Error("Invalid props.");
}

In order to set the propTypes of MyComponent, is it possible to do something like:

MyComponent.propTypes = FirstComponentPropTypes | SecondComponentPropTypes;

?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As you pointed out:

MyComponent is a "generic" component which renders A if foo is present or B if bar is present.

And it's definition is function MyComponent({ foo, bar }) { ... }

In order to avoid complex solutions, I suggest you to move the conditional logic outside of MyComponent. In this way you will need a single propType definition for MyComponent without duplicating the propType definitions of the other two components. The type your component will check is element, a common type shared by all React's elements.

MyComponent.propTypes = {
    elementToRender: PropTypes.element
};

So you need to adapt your component definition:

function MyComponent({ elementToRender }) { ... }

And the way it is used:

const getComponentToRender = (foo, bar) => {
   if (foo) {
     return <FirstComponent foo={foo} />;
   } else if (bar) {
     return <SecondComponent bar={bar} />;
   } else {
     return null;
   }
}

const element = getComponentToRender(foo, bar)

Your jsx:

{!element && <YourErrorComponent />}
{element && <MyComponent elementToRender={element} />}

You can always put your conditional logic inside the component without using a constant or variable, if you want.

Benefits

The biggest benefit of this approach is that your MyComponent doesn't need to know anything about yours FirstComponent or SecondComponent types. And you can always choose to use another component to pass to MyComponent without changing it.

Moreover, you have a single point in the code where types are defined and you don't have any dependencies between them.

Also, you are not getting props in one point and then using them in a condition far away from it.

A final consideration

To keep you code easy to read, I suggest you to avoid using a specific prop for an element. Use props.children instead:

    {element && <MyComponent>{element}</MyComponent>}

This is a more React-ish (natural) way to show a component inside another one: the children props exists to this purpose.

Moreover, you can put (again) a fallback logic inside MyComponent:

function MyComponent({ children }) {
    if (children) {
        return <div className="container">{children}</div>
    }
    
    return <p>children is missing</>
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I assume you mean | as in you want to take the union of the two sets? You can just merge the two objects with something like Object.assign():

const FirstComponentPropTypes = {
   foo: PropTypes.any,
};

const SecondComponentPropTypes = {
   bar: PropTypes.any,
};

function MyComponent({ foo, bar }) { ... }

MyComponent.propTypes = Object.assign({}, SecondComponentPropTypes, FirstComponentProptypes);
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