1

We have a simple React application where the parent component (ShopItem) renders multiple child components (CommentCard) in a loop.

const ShopItem = ({ item }) => {
    const [comments, setComments] = useState(item.comments)

    return (
        <div>
            <div className="item_title">
                item.title
            </div>
            <div className="item_comments">
                {comments.map((comment) => {
                    return (
                        <CommentCard
                            commentId={commentId}
                        />
                    )
                })}
            </div>
        </div>
    )
}

CommentCard component then internally calls API to fetch comment information and then render it on screen. Here is the structure of the item we receive in ShopItem props

{
    title: "Bucket"
    price: 90
    comments: [
        8993,
        8992,
        8991,
        8990,
        ..
        ..
        ..
    ]
}

We want to apply lazy loading for the Comment section. For example, in starting it should render the first 5 CommentCards only and when the user starts scrolling it should render the next five and so on. As we already have a list of all comments posted on items (in form of the array), we do not need to fetch comment ids from the server, we just need to manage the list we already received as props.

We tried to use React.lazy and React.suspense but those are not fulfilling our requirements. I am not looking for a fully functional solution, I am looking for an approach here.

Alex
  • 1,406
  • 2
  • 18
  • 33
  • Sounds like you referring to an [Intersection observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). Look for examples of React implementations, should be pretty simple. – tomleb May 01 '22 at 19:11
  • You haven't described the problem explicitly so it's not clear what technique best fits your requirements (e.g. do you want to _append_ new comments on each "get next comment group" event, or replace the current five with the next five, etc.). In addition to the Intersection Observer API, you can also query "virtual list". – jsejcksn May 01 '22 at 22:43

0 Answers0