Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!