React styles prop returns [object object] for array?

I have this very basic component:

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

      

Unfortunately it creates this html:

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

      

Why is this giving me [object object] instead of inline styles? Obviously I don't need to use an array here, but I am making a more complex component.

What am I doing wrong?

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

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

+3


source to share


2 answers


The problem (as said) is that you are assigning the style property to an array, but an object is expected. So just 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 lodash or underscore dependency. This will work if you have defined TileStyles something like:

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

      

If you don't need a dependency _

, it can be done manually, but it can be a problem.



Update 2016-03-29: Instead of relying on the type dependency lodash

or underscore

or doing it manually, you can use the new function Object.assign

in ecmascript 2015.

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

      

Or take an example completely updated to ecmascript 2015:

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

      

+3


source


React expects the object to be passed as a styles argument, not an array, so you will need to change it to

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

      



You need to make sure TileStyles returns an object (or is) and is available within scope, otherwise create a function in class scope and call it with

this.TileStyles()

      

+3


source







All Articles