mui / mui/base-ui

[fieldset] Expose useFieldsetRootContext

Open
#3,262 2 comments 1 reaction 0 assignees View on GitHub
component: field type: enhancement
Dominant language
TypeScript
Stars
10.9k
Forks
543
Avg merge
1d 20h
Merged PRs (30d)
101

Description

# Feature request

## Summary

I'm having difficulty wrapping my head around how to properly use a `Fieldset` with existing components.

I have a radio group control, `CustomRadio`, that allows consumers to specify the orientation of the radio controls (horizontal and vertical). Because a `Fieldset.Root` requires a `renderer` to access the `aria-labeledBy`, I'm finding it difficult to structure a `FieldSet` with `Legend` and `Description` _while_ also allowing consumers to control the layout.

For example, here's the structure I want every FieldSet to have:

```tsx


{label}

{children} // Radio Control
{description && {description}}
{errors?.map((error) => (

{error}

))}


```

According to the docs, I need to pass a `renderer` to `Fieldset.Root` with the control I want to receive that prop. This works, but then the `Legend`, `Description` and `Errors` are now children of the `Radio` control. As mentioned, the `CustomRadio` control dictates layout (flex row/column). As an example, heres the desired output:

Image

If [`useFieldSetContext`](https://github.com/mui/base-ui/blob/d917db9800eee49cdc84a1e7a301d9e92925b04a/packages/react/src/fieldset/root/FieldsetRootContext.ts#L16) was exposed I could obtain the `aria-labelledby` and pass it to my control manually.

### Workaround

I was able to create my own provider to capture the `aria-labeledby`.

```tsx
const fieldSetContext = createContext<{ ['aria-labelledby']: string }>({ 'aria-labelledby': '' });
const FieldSetProvider = (props: any) => (

{props.children}

);
export const useFieldSetContext = () => useContext(fieldSetContext);
```

```tsx
}>
```

Seems strange, maybe I'm structuring this incorrectly. Thanks for the feedback!

## Motivation

Building consistent Field, Fieldset controls with higher-order components.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.