Wednesday 22 May 2024

Render HTML Content and Handle Navigation in React Native

Rendering HTML content in React Native and handling navigation can be accomplished using a combination of libraries and techniques. Here's a step-by-step guide to achieve this:

Step 1: Install Required Libraries

First, you need to install the necessary libraries. We'll use react-native-render-html for rendering HTML content and react-navigation for handling navigation.

1. Install react-native-render-html:

npm install react-native-render-html


2. Install react-navigation and related dependencies:

npm install @react-navigation/native @react-navigation/stack


3. Install additional dependencies required by react-navigation:

npm install react-native-screens react-native-safe-area-context


4. Install the required peer dependencies:


npm install react-native-gesture-handler react-native-reanimated @react-native-community/masked-view


Step 2: Setup react-navigation


1. Import and setup navigation container in your main entry file (e.g., App.js):


import * as React from 'react';

import { NavigationContainer } from '@react-navigation/native';

import { createStackNavigator } from '@react-navigation/stack';

import HomeScreen from './screens/HomeScreen';

import DetailScreen from './screens/DetailScreen';

 

const Stack = createStackNavigator();

function App() {

  return (

    <NavigationContainer>

      <Stack.Navigator initialRouteName="Home">

        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Screen name="Detail" component={DetailScreen} />

      </Stack.Navigator>

    </NavigationContainer>

  );

}

export default App;


2. Create your screens (e.g., HomeScreen.js and DetailScreen.js):


// screens/HomeScreen.js

import React from 'react';

import { View, Text, Button } from 'react-native';


const HomeScreen = ({ navigation }) => {

  return (

    <View>

      <Text>Home Screen</Text>

      <Button

        title="Go to Detail"

        onPress={() => navigation.navigate('Detail', { content: '<p>This is HTML content</p>' })}

      />

    </View>

  );

};


export default HomeScreen;


// screens/DetailScreen.js

import React from 'react';

import { View, Text } from 'react-native';

import RenderHTML from 'react-native-render-html';


const DetailScreen = ({ route }) => {

  const { content } = route.params;

  return (

    <View>

      <RenderHTML

        contentWidth={contentWidth}

        source={{ html: content }}

      />

    </View>

  );

};


export default DetailScreen;


Step 3: Render HTML Content


To render HTML content, we use react-native-render-html. This library supports a wide range of HTML tags and styles.


Modify your DetailScreen to render HTML content:


// screens/DetailScreen.js

import React from 'react';

import { useWindowDimensions } from 'react-native';

import { ScrollView } from 'react-native';

import RenderHTML from 'react-native-render-html';


const DetailScreen = ({ route }) => {

  const { content } = route.params;

  const { width } = useWindowDimensions();


  return (

    <ScrollView>

      <RenderHTML

        contentWidth={width}

        source={{ html: content }}

      />

    </ScrollView>

  );

};


export default DetailScreen;


Handling Navigation Within HTML


If your HTML content contains links that should navigate to different parts of your app, you need to handle link clicks. This can be done by customizing the `a` tag rendering behavior.


Handle link navigation within `DetailScreen`:


// screens/DetailScreen.js

import React from 'react';

import { useWindowDimensions, Linking,  ScrollView } from 'react-native';

import RenderHTML from 'react-native-render-html';

import { useNavigation } from '@react-navigation/native';


const DetailScreen = ({ route }) => {

  const { content } = route.params;

  const { width } = useWindowDimensions();

  const navigation = useNavigation();

 

  const renderers = {

    a: ({ tnode, ...props }) => (

      <Text

        style={{ color: 'blue' }}

        onPress={() => {

          // Custom navigation logic

          const href = tnode.attributes.href;

          if (href.startsWith('/')) {

            // Example: Navigate to a screen within the app

            navigation.navigate('AnotherScreen', { path: href });

          } else {

            // External link

            Linking.openURL(href);

          }

        }}

      >

        {tnode.children[0].data}

      </Text>

    ),

  };


  return (

    <ScrollView>

      <RenderHTML

        contentWidth={width}

        source={{ html: content }}

        renderers={renderers}

      />

    </ScrollView>

  );

};


export default DetailScreen;


In this example, when a link is clicked, it checks if the link is an internal or external link. Internal links navigate to another screen within the app, while external links open in the device's default web browser.

Conclusion

By following these steps, you can render HTML content in a React Native application and handle navigation both within your app and to external URLs. Customize the renderers object to handle other HTML elements and styles as needed.

No comments:

Post a Comment