user3271166
user3271166

Reputation: 623

React not rendering component

This is my code:

var Item = React.createClass({
    render: function () {
        return (
                React.createElement('div', {},
                        React.createElement('span', {}, this.props.a),
                        React.createElement('span', {}, this.props.b)
                        )
                );
    }
});

var RParent = React.createClass({
    getInitialState: function () {
        return {messages: []};
    },
    addMess: function (data) {
        var self = this;
        self.state.messages.push({
            a: data.a,
            b: data.b
        });
        this.setState({messages: self.state.messages});
    },
    render: function () {
        var messages = this.state.messages;
        return (
                React.createElement('div', {},
                        React.createElement(Item, messages))
                );
    }
});

var box = ReactDOM.render(React.createElement(RParent), document.getElementById('parentDiv'));

function render(a, b) {
    box.addMess({
        a: a,
        b: b
    });
}

Data is sent to the render function. It appears that somehow the properties are not reaching the render function of the Item as they appear to be undefined when I try print them to console.

Any ideas why this might be happening?

The problem is that nothing is rendered into the "parentDiv". It just remains blank. However, on inspecting the elements, I can still see two "span" children under it (which were not created in html or anywhere else except here). But those span elements have no content.

Upvotes: 0

Views: 339

Answers (1)

Amoolya S Kumar
Amoolya S Kumar

Reputation: 1468

I think there's a fundamental problem to your code. You are trying to pass 'a' and 'b' to your react component through an external function 'render' that seems to be invoking one of the component's functions. This is wrong.

You should pass 'a' and 'b' to your React component RParent as props. Whenever the value of 'a' and 'b' change, your parent component will automatically rerender.

var Item = React.createClass({
render: function () {
    return (
            React.createElement('div', {},
                    React.createElement('span', {}, this.props.a),
                    React.createElement('span', {}, this.props.b)
                    )
            );
}
});

var RParent = React.createClass({
getInitialState: function () {
    return {messages: []};
},
,
render: function () {
    var messages = this.props.messages;
    return (
            React.createElement('div', {},
                    React.createElement(Item, messages))
            );
}
});

ReactDOM.render(
    (<RParent messages= {'a': a, 'b': b} />)
    , document.getElementById('parentDiv'));

Upvotes: 1

Related Questions