Skip to content

Commit

Permalink
refactor: adjust className application order
Browse files Browse the repository at this point in the history
Fixes #3912
  • Loading branch information
quantizor committed Mar 23, 2023
1 parent 4d4e63c commit 1e3ffeb
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
13 changes: 11 additions & 2 deletions packages/styled-components/src/models/StyledComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,16 @@ function useInjectedStyle<T extends object>(

function resolveContext<Props extends object>(
attrs: AttrsArg<Props>[],
props: Props,
props: React.HTMLAttributes<Element> & Props,
theme: DefaultTheme
) {
const context: ExecutionContext &
Props & { class?: string; className?: string; ref?: React.Ref<any> } = { ...props, theme };
Props & { class?: string; className?: string; ref?: React.Ref<any> } = {
...props,
// unset, add `props.className` back at the end so props always "wins"
className: undefined,
theme,
};
let attrDef;

for (let i = 0; i < attrs.length; i += 1) {
Expand All @@ -91,6 +96,10 @@ function resolveContext<Props extends object>(
}
}

if (props.className) {
context.className = joinStrings(context.className, props.className);
}

return context;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/styled-components/src/test/attrs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ describe('attrs', () => {

expect(TestRenderer.create(<Comp className="something" />).toJSON()).toMatchInlineSnapshot(`
<div
className="sc-a sc-b something foo meow nya"
className="sc-a sc-b foo meow nya something"
/>
`);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/styled-components/src/utils/joinStrings.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* Convenience function for joining strings to form className chains
*/
export function joinStrings(a: string | undefined, b: string): string {
return a && b ? `${a} ${b}` : a || b;
export function joinStrings(a?: string, b?: string): string {
return a && b ? `${a} ${b}` : a || b || '';
}

export function joinStringArray(arr: string[], sep?: string): string {
Expand Down

0 comments on commit 1e3ffeb

Please sign in to comment.