I would like to create a styled-component
with a function, taking element as an argument, which I create with React.createElement
call.
const StyledComponent = (element) => styled(element)`
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
`;
const myComponent = (props) => {
const element = React.createElement('div', null, `Hello World!`);
return (
StyledComponent(element)
);
}
This results in following error:
Uncaught Error: Cannot create styled-component for component: [object Object].
I am probably missing something, but am unable to figure it out.
Felix answer was almost right, but you still need to pass the className property in the inline component function in order to get the styles defined in your styled component applied.
I was able to find the right answer in this thread, I decided to use the JSX-syntax, If you need to pass refs, use React.cloneElement instead.
Complete example:
const StyleMyElement = (Element) => styled(({ className }) => <Element.type {...Element.props} className={className} />)`
position: absolute;
top: 0;
...
`;
...
const element = () => React.createElement('div', null, `Hello World!`);
const StyledComponent = StyleMyElement(element);
return (
<StyledComponent />
)