I tried to create a variable and a for loop inside of a functional component to show the rating stars in a product but when I try to compile it, it keeps giving me the same error :
SyntaxError: Rating.js: Unexpected token, expected ")"
for(let i=0; i<4; i++)
{
if({value}>i && {value}<i+1) {
^
stars.push(
<i
key={i}
I don't know if you can't put a for loop inside of a functional component, if there's something extra I don't know that I shouldn't be doing or if I really have a syntax error.
The full code of the component:
import React from 'react'
const Rating = ({value, text, color}) => {
let stars = [];
for(let i=0; i<4; i++)
{
if({value}>i && {value}<i+1) { //<--
stars.push(
<i
key={i}
style={{color}}
className={
'fas fa-star-half-alt'
}
/>
)} else if({value}>i) {
stars.push(
<i
key={i}
style={{color}}
className={
'fas fa-star'
}
/>
)} else {
stars.push(
<i
key={i}
style={{color}}
className={
'far fa-star'
}
/>
)
}
}
return (
<div className='rating'>
<span>
{stars}
</span>
</div>
)
}
export default Rating
The root cause that you are using interpolation in a wrong way. You don't need to use {} outside of your JSX template, that is why JS blames {value} your if statement is JS code, you need to use {} when you want to embed some JS value into your JSX template e.g. <span>{value}</span>
import React from 'react'
const Rating = ({value, text, color}) => {
let stars = [];
for(let i=0; i<4; i++)
{
if(value > i && value < i+1) {
stars.push(
<i
key={i}
style={{color}}
className={
'fas fa-star-half-alt'
}
/>
)} else if( value > i) {
stars.push(
<i
key={i}
style={{color}}
className={
'fas fa-star'
}
/>
)} else {
stars.push(
<i
key={i}
style={{color}}
className={
'far fa-star'
}
/>
)
}
}
return (
<div className='rating'>
<span>
{stars}
</span>
</div>
)
}
export default Rating