Home > Enterprise >  React - Create Error Checking for Props in Components
React - Create Error Checking for Props in Components

Time:01-10

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
}

CodePudding user response:

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");
    }
  }
};

CodePudding user response:

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...
}
  •  Tags:  
  • Related