Greg
Greg

Reputation: 8915

How to override a React component's CSS using emotion CSS?

In the below example, how to apply background-color:green to the <Test/> component without having to edit the <Test/> component directly?

/** @jsx jsx */
import { css, jsx } from "@emotion/core";
import React from "react";


function Test() {
    return (
        <div
            css={css`
                height: 100px;
                width: 100px;
                background-color: aqua;
            `}
        >
            Text
        </div>
    );
}

function App() {
    return (
        <Test
            css={css`
                height: 400px;
                width: 400px;
                background-color: green;
            `}
        />
    );
}

Upvotes: 3

Views: 6307

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

Test must use className prop which generated by css-in-js library (emotion in this case):

function Test({ className }) {
  return (
    <div
      className={className}
      css={css`
        height: 100px;
        width: 100px;
        background-color: aqua;
      `}
    >
      Text
    </div>
  );
}

Therefore:

// Will use the styling defined in `Test` component (default)
<Text/>

// Will use the defined styling and override the default when possible, 
// or add additional styling.
// i.e using background-color will override it
// using background-border will *add* a style
<Text css={...}/>

// Same as above, usually used with 3rd party css.
<Text className="someOtherCss" />

Upvotes: 3

Related Questions