I'm testing a react component, but have problems using an array map where is define an anonymous arrow function, and after arrow (=>) I use curly brackets. Then the inside code could not be executed. The code call to other component called Star that use react icons to draw a star using FaStar. Any way, I had to change the curly brackets for parenthesis and work with out problems.
Basically, my question what is the difference to use curly brackets or use parenthesis, with map and an arrow anonymous function?. When could be used parenthesis or curly brackets?
thanks for your help. Best Reagrds
This is the code not working (using curly brackets after the map's anonymous function)
import React from 'react'
import { useState } from 'react'
import Star from './Star'
const StarRating = ({totalStars}) => {
const [selectedStars, setSelectedStars] = useState(0)
const starArray = arrayLenght => [...Array(arrayLenght)]
console.log("totalStarts", totalStars)
return (
<>
{starArray(totalStars).map((n, i) => {
<Star
key={i}
selected={selectedStars > i}
onSelect={() => setSelectedStars(i + 1)}
/>
})}
</>
)
}
export default StarRating
This code works fine (using parenthesis after the map's anonymous function)
import React from 'react'
import { useState } from 'react'
import Star from './Star'
const StarRating = ({totalStars}) => {
const [selectedStars, setSelectedStars] = useState(0)
const starArray = arrayLenght => [...Array(arrayLenght)]
console.log("totalStarts", totalStars)
return (
<>
{starArray(totalStars).map((n, i) => (
<Star
key={i}
selected={selectedStars > i}
onSelect={() => setSelectedStars(i + 1)}
/>
))}
</>
)
}
export default StarRating
The difference is related to the braces.
Without the braces a return
is implicit while with the braces, you'll need to do an explicit return
.
This below
<>
{starArray(totalStars).map((n, i) => {
<Star
key={i}
selected={selectedStars > i}
onSelect={() => setSelectedStars(i + 1)}
/>
})}
</>
Would be changed to this.
<>
{starArray(totalStars).map((n, i) => {
return <Star
key={i}
selected={selectedStars > i}
onSelect={() => setSelectedStars(i + 1)}
/>
})}
</>