I’ve got a React application that is a dashboard, to which I’d like to add a while-label feature. Every client shall have a dynamic styled-components theme with their branding which is loaded upon mount.
For the proof of concept, I’ve added <ThemeProvider>
, passing the custom theme and all works great.
Now for the second step, I moved the components to a separate TypeScript + React + Vite project that is my future UI library.
The difference is that I want to serve the components with either:
- default props that later (in the Dashboard app) should be overwritten by the custom
ThemeProvider
values - or, without specifying any pre-defined props so they are added upon the render, not build
However, this does not work. It seems like the component does not respond to providing new props.
Basic component (Hello.tsx) in the external UI library:
import styled from 'styled-components'
type Props = {
theme?: {
red: string
}
text?: string
}
const Hello: React.FunctionComponent<Props> = ({text}: Props) => {
return <div>This is great! {text}</div>
}
const StyledHello = styled(Hello)`
color: ${props => {
console.log(props.theme.red);
return props.theme.red
}};
export default StyledHello
app.tsx in my Dashboard app:
export default function App({isDev}: Props) {
const theme = {
red: 'blue'
}
// ...
return (
<div>
<Hello theme={theme} text="Hi!"/>
</div>
)
// Here I tried with <ThemeProvider> wrapper too
}
The rendering result is: <div>This is great! Hi!</div>
.
The console.log()
correctly displays: blue
. Sadly, the colour is not applied and there is no custom class there.
The JS build result is:
import { jsxs as _jsxs } from "react/jsx-runtime";
import styled from 'styled-components';
const Hello = ({ text }) => {
return _jsxs("div", { children: ["This is great! ", text] });
};
const StyledHello = styled(Hello) `
color: ${props => {
console.log(props.theme.red);
return props.theme.red;
}};
`;
export default StyledHello;
I understand that might be related to the fact that the component was built without any default theme values but I would expect to apply the right look once the props are provided.
I am not hugely experienced with styled-components so perhaps I am missing something obvious. I am sure there should be a way to use it fairly simply with such use case.