Home > Enterprise >  Rendering an array of strings in React
Rendering an array of strings in React

Time:09-23

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!

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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> ) }

  • Related