简体   繁体   中英

Rendering an array of strings in React

I'm trying to render a flat array of strings in a React app, via the following:

{array.length > 0 ? (
  <div>
    <h5>Email list</h5>
    <div
      style={{
      paddingLeft: "50px",
      float: "left",
      lineHeight: "normal",
      height: "50px",
      width: "300px"
      }}
    >
    {array.map((date, index) => {
    <p key={index}>{date}</p>;
    })}
    </div>
  </div>
) : (<></>)}

I'm struggling to understand why my map function won't render anything on screen. I'm able to console log both date and index just fine, the dates definitely exist within the array and the h5 title renders as it should. However, nothing shows in the div beneath it.

If I remove the map functionality and just print a line of text, that renders. Once I add the map back in, however, it returns to an empty div. No console logs to indicate anything is wrong, either.

Any help appreciated!

The map function needs a return statement if you are adding {} brackets. Ex:

{array.map((date, index) => {
  return <p key={index}>{date}</p>;
})}

I think u are not returning the JSX inside the map method.The below code will render the list of array elements

   {array.map((date, index) => {
   return <p key={index}>{date}</p>;
   })}

I got one solution here you just need to change little bit in your code, you can add return statement after the map function and I hope it will work for you.

{array.map((date, index) => {
return (
      <p key={index}>{date}</p>;
      )
   })}

you can use this piece of code which is changed a bit.

https://codesandbox.io/s/currying-dust-uxu5jr?file=/src/App.js

{ array.map((date, index) => <p key={index}>{date}</p> ) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM