0

I am trying to declare a variable "ratingVal" which is assigned a random no inside a map operator. I want to use the variable in the rating component and also display it on the screen. However I get an error

Parsing error: Unexpected token

What is the correct syntax for declaring a variable in this case?

renderProductsCardsList(products){ return products.map( (product, i) => let ratingVal = Math.floor(Math.random() * 5) + 1 <Rating initialRating={ratingVal} readonly></Rating> <div>{ratingVal}</div> ) } 
0

3 Answers 3

3

You can't have a declaration statement within an arrow function with an implicit return. In order to do so, use the explicit return syntax. Also, you cannot return multiple elements from within the map method. Wrap them within <React.Fragment>:

renderProductsCardsList(products){ return products.map( (product, i) => { let ratingVal = Math.floor(Math.random() * 5) + 1 return ( <React.Fragment> <Rating initialRating={ratingVal} readonly></Rating> <div>{ratingVal}</div> </React.Fragment> ) }) } 

or evaluate it while assigning

renderProductsCardsList(products){ return products.map( (product, i) => <React.Fragment> <Rating initialRating={Math.floor(Math.random() * 5) + 1} readonly></Rating> <div>{ratingVal}</div> </React.Fragment> ) } 
Sign up to request clarification or add additional context in comments.

4 Comments

There's a closing parenthesis missing after </React.Fragment>
You can have an assignment expression in an arrow function with an implicit return. What you can't have is a declaration statement.
The top code snippet looks to achieve what I want but it still throws -> Parsing error: Unexpected token
to the "let ratingVal = Math.floor(Math.random() * 5) + 1" statement. And if I delete that line it complains about the return ( line
1

Two issues :

  • Missing brackets after arrow => : you can only omit brackets if you do an implicit return in one line.
  • Floating JSX in your code : i'm not sure what you want to do. There is 2 lines of JSX floating at the end of the map method. You currently don't return anything. But i guess you want to return a Rating component.

    renderProductsCardsList(products) { return products.map( (product, i) => { let ratingVal = Math.floor(Math.random() * 5) + 1 return <Rating initialRating={ratingVal} readonly></Rating> }) }

Comments

-1

Use a function to return the product inside the map function:

function renderProductsCardsList(products) { let rating = () => { let ratingVal = Math.floor(Math.random() * 5) + 1 return (<> < Rating initialRating={ratingVal} readonly ></Rating > <div>{ratingVal}</div> </>) } return products.map(product => rating()) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.