Home > Blockchain >  propTypes should be a func console warning when passing in array of icons
propTypes should be a func console warning when passing in array of icons

Time:12-20

I have the following component,

import React from 'react';
import PropTypes from 'prop-types';
import * as HIcons from '@heroicons/react/outline';

export default function Button({ type, variant, icon, label }) {
  const { ...icons } = HIcons;
  const TheIcon = icons[icon];

  return (
    <div>
      <button type={type} className={['btn', `btn--${variant}`].join(' ')}>
        <TheIcon className="w-4 h-4 mr-2" />
        {label}
      </button>
    </div>
  );
}

Button.propTypes = {
  type: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  icon: PropTypes.oneOf[Object.keys(HIcons)],
  variant: PropTypes.oneOf(['sm', 'md', 'lg'])
};

Button.defaultProps = {
  type: 'button',
  label: 'Submit',
  icon: 'SaveIcon',
  variant: 'md'
};

and I have the following storybook stories file

import Button from '.';
import * as HIcons from '@heroicons/react/outline';

const { ...icons } = HIcons;

export default {
  title: 'Components/Buttons',
  component: Button,
  argTypes: {
    type: {
      options: ['button', 'submit', 'reset'],
      control: {
        type: 'select'
      }
    },

    icon: {
      options: Object.keys(icons),
      control: {
        type: 'select'
      }
    }
  }
};

const Template = (args) => <Button {...args} />;

export const Small = Template.bind({});
Small.args = {
  label: 'Small',
  variant: 'sm',
  icon: 'SaveIcon'
};

As far as I'm aware I'm passing in everything correctly, I can switch icons and whatnot, however, I get the following console error

Warning: Failed prop type: Button: prop type `icon` is invalid; it must be a function, usually from the `prop-types` package, but received `undefined`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.

Any help in resolving this warning would be great as I'm new to propTypes.

CodePudding user response:

change your proptypes to this

Button.propTypes = {
  type: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  icon: PropTypes.oneOf(Object.keys(HIcons)),
  variant: PropTypes.oneOf(['sm', 'md', 'lg'])
};

you mistakely write this one :

icon: PropTypes.oneOf[Object.keys(HIcons)],
  • Related