Use forwardRef w/ proptypes & eslint

I am having difficulty using forwardRef for a Button in a project using eslint and prop-types.

My attempts have led to the following errors:

  • Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
  • action is missing in props validation
  • Component definition is missing display name.

What is the correct way to use forwardRef for a Button component?

function ButtonFunction ({ action = { callback: () => {}, title: 'unknown' } }, ref) {
  return (<button ref={ref} onClick={action.callback} title={action.description} type="button">{action.icon || action.title}</button>)
}

const Button = forwardRef(ButtonFunction);

Button.displayName = 'Button';
Button.propTypes = {
  action: Action.isRequired
}

export default Button;

The code you provided is almost correct. The issue is with the way you are defining the ButtonFunction component. The ref parameter should be the first parameter, followed by the destructured action parameter. Here is the corrected code:

function ButtonFunction(ref, { action = { callback: () => {}, title: 'unknown' } }) {
  return (
    <button ref={ref} onClick={action.callback} title={action.description} type="button">
      {action.icon || action.title}
    </button>
  );
}

const Button = forwardRef(ButtonFunction);

Button.displayName = 'Button';
Button.propTypes = {
  action: Action.isRequired
};

export default Button;

With this change, the forwardRef should work correctly and the errors you mentioned should be resolved.