Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass unpacking object as parameter in Javascript or JSX?

var data = [
    {author: 'foo', comment: 'nice'},
    {author: 'bar', comment: 'wow'}
];

var CommentBox = React.createClass({
    render: function () {
        var CommentNodes = this.props.data.map(function (comment) {
            return (
                <Comment author={comment.author} comment={comment.comment}>
                </Comment>
            );
        });
        return (
            <div className="comment-box">
                {CommentNodes}
            </div>
        );
    }
});

var Comment = React.createClass({
    render: function () {
        return (
            <div className="comment-box comment">
                <h2 className="comment-author">
                    {this.props.author}
                </h2>
                {this.props.comment}
            </div>
        );
    }
});

React.render(<CommentBox data={data}/>, document.getElementById("example"));

In the piece of code, I just pass the parameter to Comment using data. Since data is a object, which similar to Python's dict. So I'm wondering, can I just pass data as the unpacking object? Like using ** is Python:

>>> def show(**kwargs):
...     return kwargs
... 
>>> items = {'a': 1, 'b': 2}
>>> print(show(**items))
{'a': 1, 'b': 2}

2 Answers

As @AlexPalcuie answers above you can use object spread to accomplish exactly what python ** operators do.

So this is equivalent to your code above:

var CommentBox = React.createClass({
    render: function () {
        var CommentNodes = this.props.data.map(function (comment) {
            return (
                <Comment {...comment}>
                </Comment>
            );
        });
        return (
            <div className="comment-box">
                {CommentNodes}
            </div>
        );
    }
});
like image 95
Davin Tryon Avatar answered Oct 31 '25 15:10

Davin Tryon


You can use the spread attributes syntax.

like image 21
Alex Palcuie Avatar answered Oct 31 '25 15:10

Alex Palcuie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!