I'm currently utilizing styled-components within a React project and I am having trouble finding documentation regarding whether or not a styled component can accept inline styles on the "style" property. For example:
The Text component has been styled as follows:
import styled from 'styled-components'
type TextProps = {
content: string
className?: string
id?: string
}
const UnstyledText: React.FC<TextProps> = ({ className, content }) => {
return (
<span
className={className}
>
{content}
</span>
)
}
const Text = styled(UnstyledText)`
font-size: '1vw'
line-height: '2vw'
`
export default Text
Usage of the Text component in a component:
import styles from './index.module.css'
import Text from '../ui/atoms/Text'
export default function Home() {
return (
<div className={styles['home-page-container']} style={{ display: 'block' }}>
<div style={{ position: 'relative' }}>
<img
src={'/_next/static/media/image.jpg'}
alt={'background'}
width="100%"
/>
<Text
style={{ position: 'absolute', left: '10%', top: '20%' }}
content="Some text i want to position"
/>
</div>
<div
style={{
width: '100%',
padding: '20%',
maxHeight: '75vh',
backgroundColor: '#F5F5F5',
}}
></div>
</div>
)
}
The inline styles of
style={{ position: 'absolute', left: '10%', top: '20%' }}
are not being recognized by the browser.
Instead, I have found a workaround where I need to include a "style" prop in the styled component and then spread the object onto the span like this:
const UnstyledText: React.FC<TextProps> = ({ className, content, style }) => {
return (
<span className={className}
style={{ ...style }}
>
{content}
</span>
)
}
If I choose not to do this, I am required to enclose the styled component in a div and apply my styles to that div, which adds unnecessary complexity to my project. I am hesitant to add a "style" prop to every component or introduce wrapper divs whenever additional styling is needed for a component. There must be an alternative solution to resolve this issue.
Any suggestions or thoughts on this matter?