32

I'm using Reactivesearch, and I'm trying to assign a const variable inside a map function. Specifically in the .map Like such:

onAllData(data, streamData) {

    return (
        <div className="grid">
        {
            data.map((item) => 
                const propertyName = item.productName;

                <div className="flex-container card" key={item._id}>
                    <div className="content">
                        <p>{propertyName}</p>
                    </div>
                </div>
            )
        }
    );
}

const propertyName = item.productName; is giving me problem. Error states unexpected token .

Is it possible?

Amir Asyraf
  • 613
  • 1
  • 7
  • 18
  • 2
    Possible duplicate of [Rendering an array.map() in React](https://stackoverflow.com/questions/38282997/rendering-an-array-map-in-react) and [How to loop inside a react const variable in the render method](https://stackoverflow.com/questions/39886262) and [Putting a variable inside render() return - React Native](https://stackoverflow.com/questions/50449877) – adiga Jan 21 '19 at 14:52
  • If your function has multiple statements your function needs a body: `x=>{x+1;return 22}`, instead of `x=>22`. You could simply do the following: `data.map(({propertyName,id})=>
    – HMR Jan 21 '19 at 14:53

2 Answers2

75

You need to go from expression syntax to the block syntax, using braces and return:

        data.map((item) => {
            const propertyName = item.productName;

            return (<div className="flex-container card" key={item._id}>
                <div className="content">
                    <p>{propertyName}</p>
                </div>
            </div>)
        })

However, you could also use destructuring to get your propertyName, and then you are back to one expression:

        data.map(({productName, _id}) =>
           <div className="flex-container card" key={_id}>
                <div className="content">
                    <p>{propertyName}</p>
                </div>
            </div>
        )
trincot
  • 317,000
  • 35
  • 244
  • 286
3

That is an improper use of arrow functions.

Fix:

data.map(({productName, _id}) => (
   <div className="flex-container card" key={_id}>
       <div className="content">
            <p>{productName}</p>
        </div>
   </div>
);
Nicholas
  • 3,529
  • 2
  • 23
  • 31
Danyal Imran
  • 2,515
  • 13
  • 21