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

110
Visualizações
React - Create Error Checking for Props in Components

Let's say I'm creating a component and I want the value of a prop I'm passing to be an integer which is less than 10. What I want is if the prop is either not an integer or is greater or equal to 10 for an error to occur in React.

Example of how I want this to work:

export default function Component (props){
    typeof(props.number) != 'number' && // raise exception
    props.number >= 10 && // raise exception
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want a more declarative approach, use "prop-types" npm package
With this approach, you segregate validation logic from rendering itself.

import PropTypes from "prop-types";

export default function App() {
  return (
    <div className="App">
      <Component number={23} />
    </div>
  );
}

function Component(props) {
  return "Component rendered";
}

Component.propTypes = {
  number: function (props, propName) {
    if (typeof props[propName] !== "number" || props[propName] >= 10) {
      throw new Error("Invalid prop");
    }
  }
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Consider simply throwing an exception:

export default function Component (props){
    if (typeof(props.number) != 'number' || props.number >= 10) {
        throw new TypeError("Invalid property number. Must be numeric and < 10.")
    }

    // Your other code here...
}
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