Is it possible to navigate to in-page URL fragment subresources with react-native-render-html as implementing browser behavior?

479 views Asked by At

Is it possible to navigate to in-page URL fragment subresources with react-native-render-html as implementing browser behavior? Here is an example. Given this snippet for the html prop:

<h1 id="title">The Title</h1>
<div style="width:50px;height:200px;">
...
</div>
<a href="#title">Scroll to The Title</a>

When a user presses the "Scroll to The Title" anchor, I would like to contain ScrollView to scroll to "The Title" header. Linking.openURL is not working can you suggest me the way?

1

There are 1 answers

0
Jules Sam. Randolph On

Implementing this feature is very specific to the underlying HTML structure, so there is not an absolute, generic answer. That is why this feature will not be provided by this library. However, there is a good step by step guide in this tutorial I wrote for V6.

I'll summarize the important steps below:

  1. Thanks to custom renderers, we can map the coordinates of each target with their id in a cache object (Scroller in the above tutorial) by using onLayout prop. Beware that those coordinates are relative to the parent View.
  2. In the same cache object, we store a reference to the underlying ScrollView.
  3. We define a scrollToId method in the cache object, which invokes the underlying ScrollView ref scrollTo method to scroll to the coordinates we previously mapped to the target.
  4. We set the renderersProps.a.onPress prop to a callback which will invoke the scrollToId method of the cache object.

Note that you'll need to pass the cache object to the custom renderer via a context or via renderersProps (you can then consume the prop with useRendererProp).

Those steps are freely adapted from the above tutorial and I invite you to dive in to grasp all the implementation details. Good knowledge of React hooks, context and refs is required.