Kenny Hammerlund
Kenny Hammerlund

Reputation: 506

JSX Style Var: Combining Multiples

Is there a way to combine multiple style objects to one component?

export default class Footer extends React.Component{
render(){
    var inline = {
        display: "inline-block",
        margin: "3px"
    };
    var right = {
        textAlign: "right"
    }
    var containerStyle = {
        padding: "8px",
        color: "#DDD",
        backgroundColor: "#000",
        fontSize: "12pt"
    };

    return(
        <footer style = { containerStyle }>
            <div className="inline" style = {inline}>Managed By <a href="http://www.midnighthtml.com">MidnightHTML</a></div>
            <div className="inline" style = {right}>All Rights Reserved</div>
        </footer>
    );
}

}

I would like the second div to use the "right" style as well as the "inline"

*I am not sure I am using the proper names for these items as I am fresh to React.

Upvotes: 2

Views: 37

Answers (2)

Dacre Denny
Dacre Denny

Reputation: 30360

You could do this:

var inline = {
    display: "inline-block",
    margin: "3px"
};

var right = {
    textAlign: "right"
}

...

var combination = { ...inline, ...right };

return(
    <footer style = { containerStyle }>
        <div className="inline" style = {inline}>Managed By <a href="http://www.midnighthtml.com">MidnightHTML</a></div>
        <div className="inline" style = {combination}>All Rights Reserved</div>
    </footer>
);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191936

You can combine the objects using Object.assign():

return(
    <footer style = { containerStyle }>
        <div className="inline" style = {inline}>Managed By <a href="http://www.midnighthtml.com">MidnightHTML</a></div>
        <div className="inline" style = {Object.assign({}, right, inline)}>All Rights Reserved</div>
    </footer>
);

Or object spread (stage 4 proposal - might require a babel transform):

return(
    <footer style = { containerStyle }>
        <div className="inline" style = {inline}>Managed By <a href="http://www.midnighthtml.com">MidnightHTML</a></div>
        <div className="inline" style = {{ ...right, ...inline }}>All Rights Reserved</div>
    </footer>
);

Upvotes: 3

Related Questions