React styles prop returns [object object] for an array?

gbachik picture gbachik · May 1, 2015 · Viewed 8.7k times · Source

I've got this very basic component:

Tile = React.createClass({
    render: function(){
        var styles = [
            TileStyles.tile
        ];
        return (
            <div style={styles} test="test" />
        );
    }
});

Unfortunately it is producing this html:

<div style="0:[object Object];" data-reactid=".0.$0"></div>

Why does it give me [object object] instead of the inline styles? Obviously I don't need to use an array here but I do on a more complex component.

What am I doing wrong?

UPDATE: Thanks for the answers guys but the issue is I WANT to be able to use multiple styles.

aka use TileStyles.tile and TileStyles.active under certain circumstances.

Answer

Emil Ingerslev picture Emil Ingerslev · May 2, 2015

The problem is (as already stated) that you give the style property an array, but an object is expected. So simply changing the code to this:

Tile = React.createClass({
    render: function(){

        var style = _.extend({},TileStyles.tile,TileStyles.active);

        return (
            <div style={style} test="test" />
        );
     }
});

Here _ is a dependency on either lodash or underscore. This will work if you defined TileStyles as something like:

var TileStyles = {
    tile: { width: '200px', height: '200px', backgroundColor: 'blue' },
    active: { backgroundColor: 'green' }
}

If you don't want a dependency on _, it is possible to do it by hand, but it can be a hassle.

Update 2016-03-29: Instead of relying on a dependency like lodash or underscore or doing it by hand, you can use the new Object.assign feature in ecmascript 2015.

var style = Object.assign({},TileStyles.tile,TileStyles.active);

Or take the example fully updated to ecmascript 2015:

class Tile extends React.Component {
    render() {
        const style = Object.assign({},TileStyles.tile,TileStyles.active);
        return <div style={style} test="test" />;
    }
}