Jonny
Jonny

Reputation: 1283

Extending / Overwriting styles of an imported React Component

I have two components, I have simplified the code here for brevity... The problem is, when I import ComponentB to use as a child of ComponentA, I cannot seem to change ComponentB's styling.

I am using styled components FYI.

Example:
In ComponentA, I am importing ComponentB. ComponentB is a stand alone component that has its own styling and logic encapsulated. I need to overwrite / extend some ComponentB styling when it is being used in ComponentA.

Here is a code example:

// ComponentB
import React from "react";
import * as S from "./ComponentB.styles"; // styled components

export function ComponentB() {
  return (
    <S.Container>
      <S.Content
        {...props}
      />
    </S.Container>
  )
}
// ComponentA file
import React from "react";
import { ComponentB } from "./ComponentB";
import * as S from "./ComponentA.styles"; // styled components

export function ComponentA() {
  return (
    <S.Container>
      <S.Content
        <ComponentB {...props} /> // I need to use ComponentB but change its styling
      />
    </S.Container>
  )
}

How can I use ComponentB as a child of ComponentA but change some of its styling?

Upvotes: 0

Views: 1080

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42218

ComponentB doesn't take any props, so anything that you pass to it is just going to be ignored completely. You need to edit your components such that some styling prop can go all the way through to the DOM.

It is up to you how you want to implement overriding the styles. Is it a className or a CSSProperties object? Do styles apply to S.Container, to S.Content, or can you style both through separate props with names like containerStyle and contentStyle?

You can wrap the entire ComponentB in a styled(ComponentB) declaration and what this does is create a className prop with the correct styles (docs link). In order for this to work, your ComponentB must take this className and pass it along such that it eventually gets attached to the DOM.

Upvotes: 1

Related Questions