javascriptreactjsarray-map

nested array maps not rendering in react return


I have a react return like so:

return (
    <div className="App">
      {data && (
        <div>
            {data.map((d) => {
              return (
                <div key={d.id}>
                  <div>{d.string}</div>
                  <div> {d.array.map((el) => {
                        <div>{el}</div>
                  })}
                  </div>
                </div>
              );
        </div>
      )}
    </div>
  );

Each {el} doesn't render but the array exists, if I try and render {d.array[0]} the first index of the array is rendered, so I'm not the issue. I don't get an error and nothing breaks. Is it a react issue or a javascript issue, or is my syntax wrong.


Solution

  • You need to add a key to each children of your second map so React knows each one is different:

    return (
    <div className="App">
      {data && (
        <div>
            {data.map((d) => {
              return (
                <div key={d.id}>
                  <div>{d.string}</div>
                  <div> {d.array.map((el, index) => {
                        return <div key={index}>{el}</div>
                  })}
                  </div>
                </div>
              );
        </div>
      )}
    </div>
    );