I'm trying to extend styles for a react component using styled-components
but is not working. AFAIK, I'm doing it the right way, but perhaps I'm missing something... Here is what I have:
import React from "react"; import styled from "styled-components"; const TextContainer = ({ text }) => { return <p dangerouslySetInnerHTML={{ __html: text }} />; }; const Paragraph = styled(TextContainer)` background: red; `; class Home extends React.Component { render() { const { t } = this.props; return <Paragraph text="This is a test" />; } } export default Home;
Of course, the expected result is to have a red background on p
, but right now the output looks like this:
Any idea on how to solve this? Probably I'm missing something, but I can't realize what.
Thanks is advance!
One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.
As of styled-components v4 the withComponent API is now a candidate for deprecation. In all likelihood, you probably want to use the new "as" prop to simply switch what element/component being rendered since the withComponent API is destructive toward styles if the lowest-wrapped component is a StyledComponent.
In SCSS, you can use variables and formulas for expressing colors, font sizes, widths and spacing variants. However, when you switch from SCSS to styled components, the syntax isn't valid anymore. Styled component files are CSS-in-JS, so they are actually JavaScript files.
As stated in documentation:
The styled method works perfectly on all of your own or any third-party components, as long as they attach the passed className prop to a DOM element.
Example
// This could be react-router-dom's Link for example, or any custom component const Link = ({ className, children }) => ( <a className={className}> {children} </a> ); const StyledLink = styled(Link)` color: palevioletred; font-weight: bold; `; render( <div> <Link>Unstyled, boring Link</Link> <br /> <StyledLink>Styled, exciting Link</StyledLink> </div> );
Ref: https://www.styled-components.com/docs/basics#styling-any-component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With