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

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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