Dynamically adding content to referenced React child depending on viewport height

Viewed 71

I have implemented a proof of concept to illustrate what I try to achiev https://codesandbox.io/s/html-react-parser-forked-wcxv8?file=/src/index.js

I render an article content, which is fetched from the API but I used an example.html file for simplicity. I need to parse it using html-react-parser because we need to do some transformations before rendering it, but I omitted that part as it's not relevant for the scope of this issue.

Once we have it parsed and rendered, I've added an effect to insert an advertisement banner with a distance of twice the viewport height. As you can see, 4 or 5 banners will be inserted, depending on your viewport height, but that's not the amount of banners that should be inserted as the article continues and the conditions to still apply. Hence, we should see more banners.

What am I doing wrong? Thanks!

2 Answers

It looks like the parsed HTML returns an object of length 112, where the odd numbered indices are string types. By filtering out the elements that are strings and inserting at index + viewPortDistance, you get the correct insertion positions.

I have added console statements to ensure that the ads are actually inserted after the correct nodes.

https://codesandbox.io/s/html-react-parser-forked-0476i

The issue is not the amount of ads, but their position. Your array of articles has 116 elements, but the ref.current.children only 56.

In order to force the number of children to match the article nodes, you can wrap each item in the article array in the span of its own. That way, the articles and the children count will be the same and allow for equal distribution of ads. You can see that in here:

https://codesandbox.io/s/html-react-parser-forked-gvvmd?file=/src/index.js

Related