Search code examples
reactjsreact-props

How to validate props that are passed to a component by value?


I've got a component that accepts value prop.

const MyComponent = ({ value }) => { ... }

I want this value to always be a number that is greater than 0 and less than 1000.

I only want to validate this for testing purposes in case I'm passing wrong value to the component so that I know immediately that I did something wrong.

Should I just write simple if statement that throws an error? Something like this?

const MyComponent = ({ value }) => { 
  if (value < 0 || value > 1000) {
    throw new Error("Value is not in range");
  }
}

Is there a better way?

Thanks for your help :)


Solution

  • Well, I don´t remember what I was trying to achieve back then but I know now what I was looking for, which is Custom PropType validator

    MyComponent.propTypes = {
      value: (props, propName, componentName) => {
        const val = props[propName];
    
        if (val < 0 || val > 1000) {
          return new Error(
            'Invalid prop `' + propName + '` supplied to' +
            ' `' + componentName + '`. Validation failed.'
          );
        }
      }
    };
    

    Maybe someone will find it useful in the future :)