Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending styles with styled-components not working

Tags:

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:

enter image description here

Any idea on how to solve this? Probably I'm missing something, but I can't realize what.

Thanks is advance!

like image 357
sebazelonka Avatar asked Jan 09 '19 15:01

sebazelonka


People also ask

How can you apply dynamic styles to styled-components?

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.

Is styled-components deprecated?

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.

Can you use styled-components with SCSS?

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.


1 Answers

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

like image 130
Mosè Raguzzini Avatar answered Oct 27 '22 17:10

Mosè Raguzzini