H Varma
H Varma

Reputation: 640

Issue with Reacts render method :Giving Parsing error

Im getting the following error Parsing error: Unexpected token, expected ",",for the below code

class ProductDetails extends React.Component{
constructor(){
    super();
    this.state = {timer:0};
}
start = () => {
    this.setState({timer:this.state.timer + 1});
}
componentDidMount(){
    setInterval(this.start,1000)
}
render(){
    var data = [{ _id:12345,
                pdtName:"Gaming Laptop",
                pdtPrice:35000,
                pdtDescription:"An excellent choice for great gaming experience",
                img:'images/Laptop.jpg',
                rating:5,
                isDiscontinued:false

            }];

    return(
            <h3>Timer: {this.state.timer} </h3>

             data.map(product =>{
                return <Product pimg={product.img} pid = {product._id} pname = {product.pdtName} pprice = {product.pdtPrice} pdesc = {product.pdtDescription} 
                 prating = {product.rating} pisdiscon = {product.isDiscontinued} key={product._id}/>
            })

        )
}

}

When I remove

Timer: {this.state.timer}

from render() Im not getting the error.Simillarly if i remove data.map leaving not getting error..But when using both getting the above error.How to fix it?

Thanks

Upvotes: 0

Views: 69

Answers (2)

Nikita Madeev
Nikita Madeev

Reputation: 4380

React component can return only one element. You can wrap return inside another element, e.g. <div>...</div>, or use React.Fragment which not adding extra nodes to the DOM.

return (
    <React.Fragment>
        <h3>Timer: {this.state.timer} </h3>
        {data.map(product => {
            return (
                <Product
                    pimg={product.img}
                    pid={product._id}
                    pname={product.pdtName}
                    pprice={product.pdtPrice}
                    pdesc={product.pdtDescription}
                    prating={product.rating}
                    pisdiscon={product.isDiscontinued}
                    key={product._id}
                />
            );
        })}
    </React.Fragment>
);

Upvotes: 2

Manikandan J
Manikandan J

Reputation: 164

render() function should return only one element. In your case it is returning 2 elements which are <h3> and <Product>. You can resolve this by using <React.Fragment> as mentioned above or simply put everything inside <div>

Upvotes: 1

Related Questions