primitives icon indicating copy to clipboard operation
primitives copied to clipboard

[react/form] Fix Form.Message not being able to be used outside a Form.Field

Open DGiannaris opened this issue 1 year ago • 1 comments

Description

Closes: #2279

This PR regards an issue where users receive an error when using Form.Message outside of a Form.Field, even when following the documentation and specifying the name prop.

The Problem

The root cause is in the useContext hook within createContext.tsx, which throws an error immediately upon detecting a missing context.

The Changes

This PR introduces the following changes to try and solve that:

  • Enhances the useContext hook in createContext.tsx:

    • Adds an options object parameter with an isOptional prop
    • Checks if the context is optional and returns an empty object if so, preventing unintended errors
  • Improves FormMessage implementation:

    • Prioritizes using the name prop to link Field.Message to a Form.Field when available
    • Falls back to using the form context if name is not provided
    • Throws an appropriate error when both Form.Field context and name prop are absent.
  • Updates Form.stories.tsx:

    • Modifies a Form.Message usage to be out of context, enabling Cypress tests to also check for this scenario.

DGiannaris avatar Aug 01 '24 17:08 DGiannaris