IB MR
IB MR

Reputation: 385

Array.map index is undefined?

I have the following code in my React:

{
    comments.map((comment, index) =>
        console.log({index}), 
        <Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
    )
}

However, this returns me error that 'index' is not defined no-undef on the console.log line. This is the state:

const [comments,setComments] = useState([[]])

Why does this happen?

Upvotes: 2

Views: 1935

Answers (3)

Favio Figueroa
Favio Figueroa

Reputation: 304

you need to add { } in your array function


{
    comments.map((comment, index) => {
        console.log(index), 
        return <Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
    )}
}

Upvotes: 1

Omri Attiya
Omri Attiya

Reputation: 4037

You need to return an an element from map function. Here you just try what exactly? I think you just need to wrap your function with { } and use return statement.

{
    comments.map((comment, index) => {
        console.log({index});
        return <Textfield key = {index} placeholder ="Add Comment" Id="addComment" />;
    })
}

Upvotes: 4

Ogod
Ogod

Reputation: 948

Maybe you are just missing some curly braces around your map function

{
    comments.map((comment, index) => {
        console.log(index);
        return <Textfield key={index} placeholder="Add Comment" Id="addComment" />;
    })
}

Upvotes: 2

Related Questions