Render component from prop #181
-
Is it possible to render a component that is passed as a prop using twin.macro? If I try the below example I run into a runtime error because const BaseButton = ({ component: Component = 'button', children, ...props }) => (
<Component tw="rounded-full" {...props}>{children}</Component>
); Cheers! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Doesn't look like it's possible - styled-components is hoisting the component out of the BaseButton component making Here's the compiled code: var _StyledComponent = _styled(Component).withConfig({ // < Component is hoisted up here
// sc props
})({
"borderRadius": "9999px"
});
const BaseButton = ({
component: Component = 'button',
children,
...props
}) => React.createElement(_StyledComponent, props, children); Emotion doesn't have the same behaviour: const BaseButton = ({
component: Component = 'button',
children,
...props
}) => React.createElement(Component, _extends({
css: {
"borderRadius": "9999px"
}
}, props), children); AlternativesIf it's just the element type you'd like to change, you could use the const BaseButton = ({ children, ...rest }) => (
<button tw="rounded-full" {...rest}>
{children}
</button>
)
const MyButton = () => <BaseButton as="div">Close</BaseButton> You could also use the sc element cloning feature if you want to change the styling between components: const MyButton = tw(BaseButton)`block mt-10`
// or
const MyButton = styled(BaseButton)([tw`block mt-10`]) Hope that helps 👍 |
Beta Was this translation helpful? Give feedback.
Doesn't look like it's possible - styled-components is hoisting the component out of the BaseButton component making
Component
undefined.Here's the compiled code:
Emotion doesn't have the same behaviour:
Alternatives
If it…