Home > Software design >  Add placeholder div after third element in array in React app
Add placeholder div after third element in array in React app

Time:01-16

In my React app I am rendering some blocks:

const MyBlocks = ({ id }: { id: string }) => {
  const { data, loading } = useQuery<GqlRes>(BlocksQuery, {
    ssr: false,
    errorPolicy: 'all',
    variables: {
      blocksId: parseInt(id, 10),
    },
  });

  if (loading) {
    return <CircularProgress />;
  }

  return (
    <React.Fragment>
      {data?.blocks.map((item, i) => (
        <Block key={String(i)} data={item} />
      ))}
    </React.Fragment>
  );
};

export default MyBlocks;

When there are more than 3 blocks rendered by the backend, I want to add a placeholder <div> (filled by a third party script) after the third block. So I get:

<Block>
<Block>
<Block>
<div id="placeholder" />
<Block>
<Block>

How do I do that, what's a nice solution for this?

CodePudding user response:

<React.Fragment>
  {data?.blocks.map((item, i) => (
    <>
      <Block key={String(i)} data={item} />
      { i === 2 && <div id="placeholder" /> }
    </>
  ))}
</React.Fragment>
  • Related