How to insert another Component and place it on a random position

Viewed 45

at the moment im fetching data and render it as map into my components.

{props.posts.map((post) =>(
            <PostBasic post={post}></PostBasic>
           
        ))}

My function to fetch data:

async function fetchMoreData() {
    console.log('feed ' + feed)
    const fetchedData = await axios.get('/api/fetchfeed', {params:{dataCount: feed.length}})
    console.log(fetchedData.data)
    let newData;
    if(fetchedData.data.length != 0){
      for (let i = 0; i <= fetchedData.data.length; i++) {
        setNewData([...newData, fetchedData.data[i]])
      }
      setFeed([...feed, newData])

How can I get the length of the rendered components and place another different component at a random position? The result I'm expecting for example If we got 5 Posts from fetch is:

- <PostBasic>
- <MyOtherComponent> <---- Randomly placed
- <PostBasic>
- <PostBasic>
- <PostBasic>
- <PostBasic>

How to achieve this? Thanks

2 Answers

You can use Math.random() to get a random number and then inside map you can push that component with post component:

let randomIndex = parseInt(Math.random()*props.posts.length);

{props.posts.map((post, index) => (
    index == randomIndex ?
      <>
            <MyOtherComponent />
            <PostBasic post={post}></PostBasic>
      </>
    :
      <PostBasic post={post}></PostBasic>        
))}
export default function ComponentName({ posts }) {
  const postsLength = posts.lenght;
  const randomNum = Math.floor(Math.random() * postsLength);
  return (
    <div>
      {posts.map((post, index) =>
        index == randomNum ? (
          <AnotherPostBasic post={post} />
        ) : (
          <PostBasic post={post} />
        )
      )}
    </div>
  );
}

You can get posts length easily using Array.lenght and get a random between 0 to post length using Math.floor(Math.random() * MAX_LENGTH);. And then you can conditionally render your component if your array index match with your random number.

Related