Home > Mobile >  React Component not rendering within map loop
React Component not rendering within map loop

Time:01-22

I am trying to render multiple components using .map on an array with some content. While I am not getting any errors in the console, the component isn't rendering in the DOM. I have tried to have subHeader be nullified, but I think it more so has something to do with the way .map is interacting with the array. Any insight would be very helpful! Here is some example code:

 const instructions = [
    {
      header: 'header 1',
    },
    {
      header: 'header 2',
      subHeader: 'subheader 1',
    },
  ];

  return (
    <div className={classes.header}>
      {instructions.map((el) => {
        <InstructionRow header={el.header} subHeader={el?.subHeader} />;
      })}
      <InstructionRow header={'ian'} subHeader={'goodman'} />
    </div>
  );

CodePudding user response:

You are not returning anything from the map(). Probably this could be a reason. Try using,

{instructions.map((el) => {
  return <InstructionRow header={el.header} subHeader={el?.subHeader}/>;
 })}

CodePudding user response:

The problem is, that you don't return anything from your map.

Either use it with a return:

return (
    <div className={classes.header}>
      {instructions.map((el) => {
        return (
            <InstructionRow header={el.header} subHeader={el?.subHeader} />;
        )
      })}
      <InstructionRow header={'ian'} subHeader={'goodman'} />
    </div>
  );

... or you can write it even shorter:

  return (
    <div className={classes.header}>
      {instructions.map((el) => (
        <InstructionRow header={el.header} subHeader={el?.subHeader} />;
      ))}
      <InstructionRow header={'ian'} subHeader={'goodman'} />
    </div>
  );
  •  Tags:  
  • Related