Style React Components with className and In Line Styles

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In this lesson, we'll learn about how you can style react components using the style prop and className prop. We will go over how these props are differant than regular html style and class properties. Style, in JSX, takes an object, camel casing the property keys like borderRadius instead of border-radius.

RentPath User 5
RentPath User 5
~ 4 years ago

the following code:

function Box(style, ...rest) { return ( <div className = 'box box--medium' style= {{ ...style}} {...rest} /> ) }

const element = ( <div> <Box style={{backgroundColor: 'lightblue'}}>small box</Box> </div> )

gives me the following error:

babel.js:61666 You are using the in-browser Babel transformer. Be sure to precompile your scripts for production - https://babeljs.io/docs/setup/ runScripts @ babel.js:61666 transformScriptTags @ babel.js:336 (anonymous) @ babel.js:327 react-dom.development.js:1101 Warning: Invalid attribute name: 0

printWarning @ react-dom.development.js:1101 warning @ react-dom.development.js:1125 isAttributeNameSafe @ react-dom.development.js:3953 setValueForAttribute @ react-dom.development.js:4109 setValueForProperty @ react-dom.development.js:4093 setInitialDOMProperties @ react-dom.development.js:7003 setInitialProperties @ react-dom.development.js:7166 finalizeInitialChildren @ react-dom.development.js:18188 completeWork @ react-dom.development.js:12031 completeUnitOfWork @ react-dom.development.js:13591 performUnitOfWork @ react-dom.development.js:13690 workLoop @ react-dom.development.js:13792 callCallback @ react-dom.development.js:1555 invokeGuardedCallbackDev @ react-dom.development.js:1594 invokeGuardedCallback @ react-dom.development.js:1451 performWork @ react-dom.development.js:13910 scheduleUpdateImpl @ react-dom.development.js:14295 scheduleUpdate @ react-dom.development.js:14234 scheduleTopLevelUpdate @ react-dom.development.js:14507 updateContainer @ react-dom.development.js:14537 (anonymous) @ react-dom.development.js:18376 unbatchedUpdates @ react-dom.development.js:14366 renderSubtreeIntoContainer @ react-dom.development.js:18375 render @ react-dom.development.js:18400 (anonymous) @ Inline Babel script:62 run @ babel.js:61531 check @ babel.js:61597 loadScripts @ babel.js:61638 runScripts @ babel.js:61668 transformScriptTags @ babel.js:336 (anonymous) @ babel.js:327 babel.js:326 [Violation] 'DOMContentLoaded' handler took 175ms

Kent C. Dodds
Kent C. Doddsinstructor
~ 4 years ago

You forgot to close </Box>:

function Box(style, ...rest) {
  return <div className="box box--medium" style={{...style}} {...rest} />
}

const element = <Box style={{backgroundColor: 'lightblue'}}>small box</Box>
Ras EL Bida
Ras EL Bida
~ 3 years ago

Great course @kent ! I believe we can strip the className after using the size prop

function Box({
  style,
  size,
  ...rest
}) {
  const sizeClassName = size ? `box--${size}` : ''
  return (
    <div
      className={`box ${sizeClassName}`}
      style={{paddingLeft: 20, ...style}}
      {...rest}
    />
  )
}
ahairshi
ahairshi
~ 3 years ago

Kent, Please update the below code in the transcript. You are using javascript notation inside the div tag.


function Box(props){
    return (
        <div
            className: 'box box--small',
            style: {paddingLeft: 20},
            {...props}
        />
    )
}
Kingsley Silas Chijioke
Kingsley Silas Chijioke
~ 3 years ago

Great course @kent ! I believe we can strip the className after using the size prop

function Box({
  style,
  size,
  ...rest
}) {
  const sizeClassName = size ? `box--${size}` : ''
  return (
    <div
      className={`box ${sizeClassName}`}
      style={{paddingLeft: 20, ...style}}
      {...rest}
    />
  )
}

Yea, this works too :)

Arnaud Vallette
Arnaud Vallette
~ 3 years ago

Thx again for this great course, Be carefull in this transcript : you can replace : className={{box ${className}}} by: {box ${className}}

Alex
Alex
~ 2 years ago

Small spelling error in first paragraph: "We will go over how these props are "differant" (should be different) than regular html style..."

Alex
Alex
~ 2 years ago

"Let's destructure the props, pull out the style prop, and call the rest of the props rest. Then we'll spread the ...rest props onto the <div>. "

What is the word "rest" in this scenario? Is it some keyword that React recognizes? Or is it some arbitrary name you gave the props?

Kent C. Dodds
Kent C. Doddsinstructor
~ 2 years ago

Thanks for the tip Alex!

So "rest" refers to "rest" syntax. It's a JavaScript feature that has unique application in JSX as I demonstrate in the video. The variable name does not have to be called "rest"

Keith Price
Keith Price
~ 2 years ago

Is there a guideline for when to use "function" and when to use "const"?

    const props = {
        className: "box--small",
        style: { marginLeft: 100 },
    }
    
    return (
      
    <div>
        <div { ...props } >
                Box
        </div>

    </div>
  );
Keith Price
Keith Price
~ 2 years ago

Why do we end the final line with a comma, given that there's not another entry after that?

    const props = {
        className: "box--small",
        style: { marginLeft: 100 },
    }
Keith Price
Keith Price
~ 2 years ago

at 1:17, what is "object shorthand"?

PJ Cabrera
PJ Cabrera
~ a year ago

Keith, you use functions for things that accept parameters. For example, at the beginning of the lesson, Box is a function that takes a parameter named props. Later on we add more parameters, such as size, className, style, and ...rest, which is a placeholder for anything else passed in.

Meanwhile, props is a const because it's an object with fixed values.

The reason why the last element in props has a comma even though there are no more elements, is a kind of cheat that allows for a defensive programming style. It's just a convention that was adopted by a few programming languages, not just JS, that makes it easier to add a new element to an object, list, etc, without inviting syntax errors. Here's a short article on the rationale: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas