Search code examples
cssreactjscodepen

Where do these styles come from in reactjs examples on codepen?


Composition-vs-inheritance React

Documentation

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

https://codepen.io/gaearon/pen/ozqNOV?editors=0010


Solution

  • When you're viewing a pen on CodePen, the styling will most likely be applied by the code in the CSS section. It's possible that there is inline CSS in the HTML, and it's also possible JavaScript is manipulating the styling inline, but in all three instances you'll be dealing with CSS code.

    The example you posted is doing all of the styling in the CSS tab. The HTML tab only contains a container for the React elements to render to.

    We'll use your FancyBorder function as an example.

    function FancyBorder(props) {
      return (
        <div className={'FancyBorder FancyBorder-' + props.color}>
          {props.children}
        </div>
      );
    }
    

    You're constructing a <div> with the class name of 'FancyBorder-' + props.color, where props.color is a variable that will be used later on.

    Continuing with your example, you use the following code to create a welcome dialog:

    function WelcomeDialog() {
      return (
        <FancyBorder color="blue">
          <h1>
            Welcome
          </h1>
        </FancyBorder>
      );
    }
    

    In this code, you're calling the FancyBorder function and passing through color="blue" which is referenced in the original function as props.color. It now runs 'FancyBorder-' + props.color to generate a class named: FancyBorder-blue.

    Now in the CSS section, you'll see your FancyBorder-blue is already setup as a class and has styling applied to it:

    .FancyBorder-blue {
      border-color: blue;
    }
    

    This specific CSS applies a blue border around the box we just created. Hopefully that clears things up.