Extending styles with styled-components not working

sebazelonka picture sebazelonka · Jan 9, 2019 · Viewed 12.7k times · Source

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!

Answer

Mos&#232; Raguzzini picture Mosè Raguzzini · Jan 9, 2019

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