Priince Abalogu Priince Abalogu - 1 month ago 8
React JSX Question

why wont react class print json unless props

I am new to react and trying to understand how to print json values to dom.

this works:

var C = React.createClass({
render: function() {
return <p>{this.props.data[0].product}</p>
}
});

var data = [
{
product:"Hello",
quantiy:2
},
{
product:"two",
quantiy:4
},
{
product:"three",
quantiy:3
}
]
React.render(<C data={data}/>, document.body);


but when i try this it doesnt work why?

var C = React.createClass({
var data = [
{
product:"Hello",
quantiy:2
},
{
product:"two",
quantiy:4
},
{
product:"three",
quantiy:3
}
]
render: function() {
return <p>{this.data[0].product}</p>
}
});


React.render(<C />, document.body);


I have created an array and called this.data[0].product but it doesnt work

Answer

Because you write this.data but data is not declared on this.

try

    var C = React.createClass({
        data: [
            {
                product: "Hello",
                quantiy: 2
            },
            {
                product: "two",
                quantiy: 4
            },
            {
                product: "three",
                quantiy: 3
            }
        ],

        render: function () {
            return <p>{this.data[0].product}</p>;
        }
    });

or

    var C = React.createClass({
        render: function () {
            var data = [
                {
                    product: "Hello",
                    quantiy: 2
                },
                {
                    product: "two",
                    quantiy: 4
                },
                {
                    product: "three",
                    quantiy: 3
                }
            ];

            return <p>{data[0].product}</p>;
        }
    });
Comments