Search code examples
reactjsinline-styles

React sees inline style attribute as a string even though I'm passing an object


When I use the JSX below to set inline styles programmatically, the page won't load. I've simplified the code to a trivial example to illustrate the problem.

const AboutPage = () => {
    let buttonStyle = { color: 'red' };
    return (
        <div>
            <input type="button" style="{buttonStyle}" value="Click Me" />
        </div>
    );
}

I get this error in the browser console:

The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

This is my first day learning React and JSX so I must be missing something obvious. But it seems like I'm doing the right thing: I'm putting an object (not a string) inside curly braces. Why does React interpret it as a string?


Solution

  • The problem was the quotes around the attribute value. In JSX, if you replace a static attribute value with JavaScript code, the code must be inside curly brackets and the bracketed code can't be quoted. This is different from how other templating languages (e.g. ASP.NET) where quotes around attributes-with-code are allowed or even required.

    When I removed the quotes around the attribute value, then it worked fine.

    <!-- bad -->
    <input type="button" style="{buttonStyle}" value="Click Me" />
    
    <!-- good -->
    <input type="button" style={buttonStyle} value="Click Me" />
    

    It seems obvious now that I figured it out, but I wasted a half-hour digging through exception callstacks and googling "how to set inline styles with react" sample code before I noticed the quotes.

    I'm posting this Q&A here in the hopes that a future JSX newbie will be able to Google for this error message and figure out what they're doing wrong. ;-)