2

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?

2
  • 2
    When function has more than one line in it, you should use curly braces. and you can directly log index without { } and then return <TextField> Commented May 29, 2021 at 18:40
  • change useState to: ([]) Commented May 29, 2021 at 18:41

3 Answers 3

4

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" />;
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your return statement should be on one line with the <Textfield .../> or surrunded by () otherwise the map function always returns undefined/null.
2

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" />;
    })
}

Comments

1

you need to add { } in your array function


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.