3

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;
            `}
        />
    );
}
4
  • In the background, emotion uses the className property. If your Test-component doesn't accept a className, emotion can't change its styles Commented Apr 27, 2020 at 9:44
  • Sorry, I'm not sure that I understand what you mean? As in provide a classname argument inside function Test( {classname} )? Commented Apr 27, 2020 at 9:54
  • Yes, see Dennis' answer below for an implementation Commented Apr 27, 2020 at 10:01
  • Another pattern to adopt will be passing of props down to the child component Commented Apr 27, 2020 at 10:05

1 Answer 1

3

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" />
Sign up to request clarification or add additional context in comments.

1 Comment

Does this mean that it is okay to call Test using <Test/>? Or should classname still be specified, e.g. <Test className="testComponent"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.