2

How do i get the the nested objects from json file in reactjs, any how iam able to get the first set of objects, but iam failing to get the nested one.

ID - {this.props.product.id} // output - 1 (works fine)

Nested details - {this.props.product[detailPage]} // gives Error

CODE :

export default class Products extends React.Component {
    constructor() {
        super();
        this.state = {
            "productdetails": false
        }
    }
    /*componentWillMount() {
        let url = "./products.json";
        Request.get(url)
            .then((res) => {
                this.setState({
                    data: res.body.data
                });
            })
            .catch(function (err) {
                alert(err);
            });
    }*/
    handleinputdata() {
        alert();
    }
    render() {
        var productdetails = this.state.productdetails;
        if (productdetails == false) {
            //var status = (<ProductsC onUserInputs={this.handleinputdata.bind(this)} />);
            var status = (<ProductsDetailComponent onUserInputs={this.handleinputdata.bind(this)} />);
        } else {
            var status = (<ProductsDetailComponent onUserInputs={this.handleinputdata.bind(this)} />);
        }
        return (
            <Grid>
                <Row>
                    <Col sm={12} className="text-center">
                        <h2>MEN'S STYLES</h2>
                        <p>To Make a Lasting Impression</p>
                    </Col>
                </Row>

                {status}

                {/*<Route path="/products" exact component={ProductsC} />*/}
                {/*<Route path="/products/:id" component={ProductDetail} />*/}
            </Grid>
        );
    }
}

ID  - {this.props.product.id} // output - 1 (works fine)

Nested details - {this.props.product[detailPage]} // gives Error

/* Products Detail Page Component starts */
class ProductsDetailComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
    }
    componentWillMount() {
        let url = "./products.json";
        var jsonParse = JSON.stringify(this.state.data);


        console.log(jsonParse);

        Request.get(url)
            .then((res) => {
                this.setState(
                    {
                        data: res.body.data

                    }
                );

                console.log('url - ' + url);
                console.log('res - ' + res.body.data);

            })
            .catch(function (err) {
                alert(err);
            });

    }
    render() {
        return (
            <Row className="products-container">
                <Col sm={12}>

                    {JSON.stringify(this.state.data[0])}
                    {
                        this.state.data.map(
                            (product, index) => (
                                <ProductDetailData key={index} product={product} />
                            )
                        )
                    }
                </Col>
            </Row>
        )
    }
}
/* Products Component ends */


// Products Starts
class ProductDetailData extends React.Component {
    handleClick() {
        //console.error('Id'+this.refs.idInputText.value);
        const { title, img, des, rs, buy, details } = this.props.product;
        this.props.onUserInputs(title, img);
    }

    render() {

        const { title, img, des, rs, buy, details } = this.props.product;

        return (
            <Col xs={12} sm={3} className="text-center product-list">
                <Card>
                    <CardImg src={img} alt="product img" />

                    ID  - {this.props.product.id} <br/>
                    img - {this.props.product.img} <br/>
                    title - {this.props.product.title} <br/>
                    des - {this.props.product.des} <br/>
                    rs - {this.props.product.rs} <br/>
                    buy - {this.props.product.buy} <br/>
                    details - {this.props.product.details} <br/>

                    {/*details - {this.props.product[detailPage]} <br/>*/}



                    <Link to="/">
                        <CardTitle>{title}</CardTitle>
                    </Link>
                    <CardText>{des}</CardText>
                    <CardText>Rs : {rs} /-</CardText>

                    <Button className='btn btn-danger'>{buy}</Button> &nbsp;
                    {/*<Button className='btn btn-primary'></Button>*/}
                    <Button onClick={this.handleClick.bind(this)} className="btn btn-primary">
                        {details}
                    </Button>
                </Card>
            </Col>
        )
    }
}

enter image description here

Not Sure What I'am missing it here, only using reactjs. when ever i try to to click on product page iam trying to show product details page and only single product data trying to display.

my JSON Code :

{
    "data": [
        {
            "id": 1,
            "title": "Jackets",
            "img": "./img/p1.jpg",
            "des": "Pure Leather Jacket",
            "rs": 9000,
            "buy": "Add to Cart",
            "details": "View Details",
            "detailPage": [
                {
                    "productDetail": "Made of Pure Leather",
                    "qty": 4,
                    "size": "S, M, L, XL, XXL",
                    "color":"white, black",
                    "AddtoCart" : "Add to Cart"
                }
            ]
        }
    ]
}
5
  • Have you tried this Nested details - {this.props.product.detailPage} ? Commented Jan 30, 2018 at 10:48
  • yes.. indeed throws error :( Commented Jan 30, 2018 at 10:48
  • Also first things first you are binding all your functions directly in render. Plz don’t do that. You have to bind your function inside a constructor always and call that reference in event handler onClick or onChange wherever required. Commented Jan 30, 2018 at 10:50
  • can u pl. update the code in answer section.. iam a newbie. Commented Jan 30, 2018 at 10:51
  • Updated please check. Commented Jan 30, 2018 at 11:02

2 Answers 2

1

Try below code.

/* Products Detail Page Component starts */
class ProductsDetailComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
    }
    componentWillMount() {
        let url = "./products.json";
        var jsonParse = JSON.stringify(this.state.data);


        console.log(jsonParse);

        Request.get(url)
            .then((res) => {
                this.setState(
                    {
                        data: res.body.data

                    }
                );

                console.log('url - ' + url);
                console.log('res - ' + res.body.data);

            })
            .catch(function (err) {
                alert(err);
            });

    }
    render() {
        return (
            <Row className="products-container">
                <Col sm={12}>

                    {JSON.stringify(this.state.data[0])}
                    {
                        this.state.data.map(
                            (product, index) => (
                                <ProductDetailData key={index} product={product} productDetails={product.detailPage} />
                            )
                        )
                    }
                </Col>
            </Row>
        )
    }
}
/* Products Component ends */


    //specify right path where this component is located
import ProductsDetailChildren from './ProductsDetailChildren';
// Products Starts
class ProductDetailData extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        //console.error('Id'+this.refs.idInputText.value);
        const { title, img, des, rs, buy, details } = this.props.product;
        this.props.onUserInputs(title, img);
    }

    render() {

        const { product, productDetails } = this.props;

        let rows = []; 
        if(this.props.productDetails){ 
            if(this.props.productDetails.length > 0){ 
                this.props.productDetails.forEach((data, i) => { 
                    rows.push(<ProductsDetailChildren key={i} qty={data.qty} productDetail={data.productDetail} size{data.size} color={data.color} AddtoCart={data.AddtoCart} />) 
                }) 
            }
        }

        return (
            <Col xs={12} sm={3} className="text-center product-list">
                <Card>
                    <CardImg src={this.props.product.img} alt="product img" />


                    ID  - {this.props.product.id} <br/>
                    img - {this.props.product.img} <br/>
                    title - {this.props.product.title} <br/>
                    des - {this.props.product.des} <br/>
                    rs - {this.props.product.rs} <br/>
                    buy - {this.props.product.buy} <br/>
                    details - {this.props.product.details} <br/>

                    {/*details - {this.props.product[detailPage]} <br/>*/}

                    product details - {rows}

                    <Link to="/">
                        <CardTitle>{this.props.product.title}</CardTitle>
                    </Link>
                    <CardText>{this.props.product.des}</CardText>
                    <CardText>Rs : {this.props.product.rs} /-</CardText>

                    <Button className='btn btn-danger'>{this.props.product.buy}</Button> &nbsp;
                    {/*<Button className='btn btn-primary'></Button>*/}
                    <Button onClick={this.handleClick} className="btn btn-primary">
                        {this.props.product.details}
                    </Button>
                </Card>
            </Col>
        )
    }
}


class ProductsDetailChildren extends React.Component { 
constructor(props) { 
super(props); 
this.state = { 

} 
} 
render() { 

const { qty, productDetail, size, color, AddtoCart } = this.props; 

return ( 
    <div>
        <ul>
            <li>Quantity: {qty}</li>
            <li>productDetail: {productDetail}</li>
            <li>size: {size}</li>
            <li>color: {color}</li>
            <li>AddtoCart: {AddtoCart}</li>
        <ul>
    </div>
) 
} 
}
Sign up to request clarification or add additional context in comments.

9 Comments

Uncaught TypeError: product.get is not a function
Can you try again.Updated my answer
yes tried, now new error > Uncaught ReferenceError: img is not defined
Ok. Change this line from <CardImg src={img} alt="product img" /> to <CardImg src={this.props.product.img} alt="product img" />
hmm..> that worked.. this is now productDetails: undefined
|
0

Please use key as 'key';

this.props.product['detailPage']

Ex:

var x = {
    "data": [
        {
            "id": 1,
            "title": "Jackets",
            "img": "./img/p1.jpg",
            "des": "Pure Leather Jacket",
            "rs": 9000,
            "buy": "Add to Cart",
            "details": "View Details",
            "detailPage": [
                {
                    "productDetail": "Made of Pure Leather",
                    "qty": 4,
                    "size": "S, M, L, XL, XXL",
                    "color":"white, black",
                    "AddtoCart" : "Add to Cart"
                }
            ]
        }
    ]
}
console.log(x.data[0]['detailPage']); 

6 Comments

if i have multiple objects ? its a sepreate json file im calling.. where should i use key ?
Please give detail? which multiple objects?
{ "id": 1, "detailPage": [ { "productDetail": "Made of Pure Leather", "qty": 4, "size": "S, M, L, XL, XXL", "color":"white, black", "AddtoCart" : "Add to Cart" } ] }, { "id": 2, "detailPage": [ { "productDetail": "Made of Pure Leather", "AddtoCart" : "Add to Cart" } ] }
Please Use this.props.product['detailPage'][0].productDetail. For first detail
If you display All detail for product "title": "Jackets", then you need to pass "index" and get like this.props.product['detailPage'][index].productDetail
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.