lostcoder
lostcoder

Reputation: 97

Expected an assignment or function call and instead saw an expression error in react if return is not present inside map statement why?

import React, { Component } from 'react'

export default class DisplayTodo extends Component {
    state = {
        todo:["eat", "sleep", "repet"]
    }
    render() {
        return (
            <div>
            {
                this.state.todo.map((value)=>{
                    <p>{value}</p>
                })
            }
            </div>
        )
    }
}

1) I know if i keep return in map it works but i want know why it failed

2)Moreover i referd to the link in for React

https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx

Now the error looks quit opposite to the explanition saying Expected an assignment or function call and instead saw an expression

3)in the react link explanation in above it is said You can put any valid JavaScript expression inside the curly braces

4) Moreover in javascript we can write like this why it is not possible in React

var a = [11,33,99]
a.map((val)=>{
console.log(val*2)
})

Upvotes: 0

Views: 329

Answers (2)

Max
Max

Reputation: 2036

So in your code

export default class DisplayTodo extends Component {
    state = {
        todo:["eat", "sleep", "repet"]
    }
    render() {
        return (
            <div>
            { <-- outer expression start
                this.state.todo.map((value)=>{
                    <p>{value}</p>  <-- inner expression
                })
            } <-- outer expression end
            </div>
        )
    }
}

You've got one outer expression, which wraps your JS code, it's completely correct. Your inner expression is also fine, because you use curly braces for JS code inside of JSX element. But, in order for React to render values from todo array, you must return each element from map callback, like that:

export default class DisplayTodo extends Component {
    state = {
        todo:["eat", "sleep", "repet"]
    }
    render() {
        return (
            <div>
            {
                this.state.todo.map((value)=>{
                    return <p key={value}>{value}</p>
                })
            }
            </div>
        )
    }
}

Or you can do:

{
  this.state.todo.map(value => <p key={value}>{value}</p>)
}

Note: I also added React keys to each todo in array, so you have some sort of uniqueness(good explanation about React keys)

Upvotes: 2

Lucas Claude
Lucas Claude

Reputation: 351

The curly braces "{}" require a return statement. If you do not want to add a return statement simply use "()" or nothing instead. ex)

this.state.todo.map((value)=>
  <p>{value}</p>
)

Upvotes: 1

Related Questions