Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a const variable inside a map function

Tags:

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?

like image 483
Amir Asyraf Avatar asked Jan 21 '19 14:01

Amir Asyraf


2 Answers

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>         ) 
like image 62
trincot Avatar answered Oct 18 '22 23:10

trincot


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> ); 
like image 38
Danyal Imran Avatar answered Oct 19 '22 00:10

Danyal Imran