Styles as Objects

Most of the time, a page's styles belong in style.css, and elements get them with className. But sometimes a style comes from your data, such as the color of a stage. Then you can give the element the attribute style. In JSX, its value isn't a text, as in HTML, but an object:

<p style={{ color: "teal", fontSize: 24 }}>Forest Stage</p>

The outer braces say "here comes JavaScript", and the inner ones are the object. Its properties are CSS properties in camelCase, as you know them from element.style in JavaScript: fontSize for font-size, backgroundColor for background-color. The values are texts, as in CSS, but a number means pixels: fontSize: 24 is 24px. (Properties without units keep their number, such as lineHeight: 1.5.)

As it's an object, a value can come from a variable:

export default function App() {
    const stageColor = "#dcfce7";

    return (
        <p style={{ backgroundColor: stageColor, padding: 8 }}>Forest Stage</p>
    );
}

A text, as in HTML, doesn't work: with style="color: teal", the app stops, and the console explains that style expects an object: Error: The `style` prop expects a mapping from style properties to values, not a string.

Instructions

Make the heading Forest Stage green and bigger: give it a style with color "green" and fontSize 32.

Give the paragraph of the Tent, Tin Robots, Saturday 21:00, a background in the color from tentColor, and a padding of 8.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

7/9

Next