ramageftw
ramageftw

Reputation: 81

Insert a React component into an array

I have a query about the best way to go about this. So i have a stateless component called <Banner/> which just displays an image and some text.

I then have an array of objects which generates a list of features on the homepage of my site. There's roughly 15 objects in this listGroups array so it renders 15 <Group/> components one after the other. The code for this is below

  {listGroups.map((group, i) => (group?.assets?.length > 0) && (
     <Group key={group.id} {...group} showTitle={i !== 0} large={i === 0} />
  ))}

I would like to insert my <Banner/> component into this list in a specific position, ideally after the first <Group/> is rendered. I can use array.splice and add the component into a specific position into the array but it isn't rendered on the page so I'm obviously missing something here.

The end result would be something like this

<Group/>
<Banner/>
<Group/>
<Group/>
<Group/>
and so on

Any help would be appreciated.

Upvotes: 1

Views: 2807

Answers (3)

joy08
joy08

Reputation: 9652

Check this and let me know if this is what you want

Sandbox

https://codesandbox.io/s/crazy-lalande-mx5oz

//Have taken limit as 10 for demo
export default function App() {
  function print() {
    let group = [];
    for (let i = 0; i <= 10; i++) {
      group.push(<Group key={i} />);
    }
    group.splice(1, 0, <Banner/>);// adding Banner at 1st index
    return group;
  }
  return <div>{print()}</div>;
}

Upvotes: 1

Jimi Pajala
Jimi Pajala

Reputation: 2368

You have various ways to achieve this.

In React you can render array of elements inside JSX, just like any other variable. If you wish to render components based some data that comes from api you could as well map your data and pass data to component. "key" property is required in both cases so React knows when structure changes.

Live example on CodeSandbox https://codesandbox.io/s/bold-grass-p90q9

const List = [
  <MyComponent key="one" text="im 1st!" />,
  <MyComponent key="two" text="im 2nd" />,
  <MyComponent key="three" text="im 3rd" />
];

const data = [
  { text: "1st string" },
  { text: "2st string" },
  { text: "3st string" }
];

export default function App() {
  return (
    <div className="App">
      <h3>Render array</h3>
      {List}
      <h3>Map from data</h3>
      {data.map(({ text }) => (
        <MyComponent key={text} text={text} />
      ))}
    </div>
  );
}

Upvotes: 1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

You can create an array of JSX.Elements e.g.

const arr: JSX.Elements[] = [];

listGroups.forEach((group, i) => {
  if(i == 1) arr.push(<Banner/>);
  // add your Groups
})

and you can render the arr.

Upvotes: 2

Related Questions