Search code examples
javascriptreactjsreact-proptypes

Is it possible to check prop types as case insensitive on React prop-types?


I wonder if there is a way to check prop types case insensitive in React. Basically, the solution should replace the following code. As far as I checked, there is no solution on the official documentation of prop-types.

Brand.propTypes = {
    name: PropTypes.oneOf([
        'google',
        'Google',
        'GOOGLE'
    ])
}

Solution

  • From the React PropTypes Docs:

    // You can also specify a custom validator. It should return an Error
    // object if the validation fails. Don't `console.warn` or throw, as this
    // won't work inside `oneOfType`.
    customProp: function(props, propName, componentName) {
      if (!/matchme/.test(props[propName])) {
        return new Error(
          'Invalid prop `' + propName + '` supplied to' +
          ' `' + componentName + '`. Validation failed.'
        );
      }
    },
    

    So with this in mind, you could write your own custom matcher like this that takes care of your requirement:

    const matchesCaseInsensitiveString = (matchingString) => {
      const matchingStringLower = matchingString.toLowerCase();
      return (props, propName, componentName) => {
        const propValue = props[propName];
        if (typeof propValue !== "string" || props[propName].toLowerCase() !== matchingStringLower) {
          return new Error('Expected ' + matchingStringLower + ' but got ' + propValue);
        }
      }
    }
    
    // example
    const propTypes = {
      google: matchesCaseInsensitiveString('GOOGLE'),
      yahoo: matchesCaseInsensitiveString('Yahoo'),
    };
    
    const props = {
      google: 'google',
      yahoo: 'Bing',
    };
    
    console.log(
      propTypes.google(props, 'google', 'MyFakeComponent')
    ); // won't return an error
    
    console.log(
      propTypes.yahoo(props, 'yahoo', 'MyFakeComponent')
    ); // will return an error

    This is a bit rough (it defaults to an .isRequired type matching check and has a pretty rudimentary warning) but you get the rough idea of how this can be accomplished.