Skip to content

feat(react): add forwardedAs prop to styled components - #1540

Open
officialasishkumar wants to merge 1 commit into
callstack:masterfrom
officialasishkumar:feat/react-forwarded-as
Open

officialasishkumar wants to merge 1 commit into
callstack:masterfrom
officialasishkumar:feat/react-forwarded-as

Conversation

@officialasishkumar

Copy link
Copy Markdown

Motivation

Closes #713

as on a styled component replaces the component it wraps. For a wrapped component that is not itself a styled component (e.g. a router Link), there is no way to change what that component renders without replacing it. forwardedAs, as in styled-components, covers that case.

Summary

  • forwardedAs is stripped from the props and passed to the wrapped component as its as prop.
  • It is ignored when as is set, and when the styled component is built from an HTML tag, so it never ends up on the DOM.
  • Added forwardedAs?: React.ElementType to the as overloads of StyledComponentWithAs, so it is typed for components created from HTML tags and for wrapped styled components. Wrapping a plain React component still returns that component's own props type, as it does for as today.
  • Docs in docs/API.md and a changeset (minor) for @linaria/react.

Test plan

On Node 22 in packages/react:

  • pnpm test — 26 tests pass, 17 snapshots unchanged; includes new tests for a wrapped custom component, a wrapped styled component, as combined with forwardedAs, and HTML tags.
  • pnpm test:dts — type tests pass, including new forwardedAs cases and a @ts-expect-error for an invalid value.
  • pnpm typecheck and eslint on the changed files are clean.

The `as` prop on a styled component replaces the component it wraps.
When the wrapped component is not a styled component (for example a
router link) there was no way to change the element rendered inside it
without replacing the component itself.

Add a `forwardedAs` prop, matching styled-components. It is removed
from the props passed down and handed to the wrapped component as its
`as` prop. It is ignored when `as` is set (the wrapped component is
replaced or already receives `as`) and when the styled component is
created from an HTML tag, so it never reaches the DOM.

The prop is added to the `as` overloads of StyledComponentWithAs, with
type tests, runtime tests and documentation in docs/API.md.

Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

forwardedAs prop similar to styled-components

1 participant