The WebView fails to show up upon triggering the onPress() event

I have a code snippet that creates a card and within this card, I want to load the URL from the card and display a webview using the 'react-native-webview' library.

import {View, Linking, TouchableNativeFeedback} from 'react-native';
import {Text, Button, Card, Divider} from 'react-native-elements';
import moment from 'moment';
import {WebView} from 'react-native-webview';

export default class DataItem extends React.Component {
  render() {
    const {title, description, publishedAt, source, urlToImage, url} =
      this.props.article;
    const {noteStyle, featuredTitleStyle} = styles;
    const time = moment(publishedAt || moment.now()).fromNow();
    return (
      <TouchableNativeFeedback
        useForeground
        onPress={() => <WebView source={{uri: url}} style={{marginTop: 20}} />}>
        <Card>
          <Text style={{fontWeight: 'bold'}}> {title || 'YEET'} </Text>
          <Divider style={{backgroundColor: '#dfe6e9', margin: 5}} />
          <Card.Image source={{uri: urlToImage}} />
          <Text style={{marginBottom: 10}}>{description || 'Read More..'}</Text>
          <Divider style={{backgroundColor: '#dfe6e9'}} />
          <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <Text style={noteStyle}>{source.name.toUpperCase()}</Text>
            <Text style={noteStyle}>{time}</Text>
          </View>
        </Card>
      </TouchableNativeFeedback>
    );
  }
}

Answer №1

It seems like you are attempting to display a webview when the card is pressed. The issue in your code lies in trying to return a component on Touchable onPress, which is not the correct approach. You should maintain the state such that when the card is pressed, the state changes to active and displays the webview.

Here's a Suggested Approach

import { View, Linking, TouchableNativeFeedback } from 'react-native';
import { Text, Button, Card, Divider } from 'react-native-elements';
import moment from 'moment';
import { WebView } from 'react-native-webview';

export default class DataItem extends React.Component {

  state = {
    showWebview: false,
  };

  render() {
    const {
      title,
      description,
      publishedAt,
      source,
      urlToImage,
      url,
    } = this.props.article;
    const { noteStyle, featuredTitleStyle } = styles;
    const time = moment(publishedAt || moment.now()).fromNow();
    return (
      <View>
        <TouchableNativeFeedback
          useForeground
          onPress={() => {
            this.setState({ showWebview: true });
          }}
        >
          <Card>
            <Text style={{ fontWeight: 'bold' }}> {title || 'YEET'} </Text>
            <Divider style={{ backgroundColor: '#dfe6e9', margin: 5 }} />
            <Card.Image source={{ uri: urlToImage }} />
            <Text style={{ marginBottom: 10 }}>
              {description || 'Read More..'}
            </Text>
            <Divider style={{ backgroundColor: '#dfe6e9' }} />
            <View
              style={{ flexDirection: 'row', justifyContent: 'space-between' }}
            >
              <Text style={noteStyle}>{source.name.toUpperCase()}</Text>
              <Text style={noteStyle}>{time}</Text>
            </View>
          </Card>
        </TouchableNativeFeedback>
        {this.state.showWebView && ( // it will show webview whew showWebview is  true.
          <WebView source={{ uri: url }} style={{ marginTop: 20 }} />
        )}
      </View>
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason behind the unexpected outcome of process.argv[3] when its value is set to '*'?

My calculator app is very straightforward: if (process.argv[3]==='+') console.log(parseInt(process.argv[2]) + parseInt(process.argv[4])); if (process.argv[3]==='-') console.log(parseInt(process.argv[2]) - parseInt(process.argv[4])); i ...

What is the best way to create a sequential number pattern of 1, 2, 3, 4 in Mongoose?

Is there a way to create a similar pattern without coding experience? I'm not familiar with coding, so looking for guidance. Here is the code snippet in question: array = 1,2,3,4,5 const note = new notedModel ({ _id: array, note: args[1] ...

collecting user input in React.js

After doing some research on React.js from this website, I stumbled upon a piece of code that left me puzzled. As far as I can tell, the checkbox for isGoing will be pre-filled as true (checked) and the numberOfGuests will be set to 2. However, I found m ...

Trigger the change-event by hand

Hey there, I'm facing an issue with manually triggering a change event. Currently, I have a selectOneMenu (similar to a dropdown in JSF) with various values. When I select a value from this dropdown list, a datatable is supposed to be updated. This ...

Enable the Drill Down feature in a Highcharts chart by interacting with a different chart through a manual click

Utilizing Highcharts for creating two charts within Angular (although that detail may not be relevant to the issue at hand) - a pie chart and a bar chart. I have both charts defined and my objective is to initiate a drill-down action in the bar chart upon ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Arranging data using jqGrid's Inline Editing Feature

Can the data on jqGrid be sorted directly on the client side while using inline editing? It appears that the data is not being sorted when the row is editable, even if the row header is clicked. ...

What could be causing the JavaScript to malfunction when combined with PHP?

Attempting to retrieve search items from Twitter using PHP curl, process, and update them every second. For this basic version, the goal is to refresh the search results for "bieber" every second. The issue seems to arise from combining PHP with JavaScript ...

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...

Submitting an HTML form to trigger a PHP function through AJAX

I am currently working on a task that involves POSTing an email address entered in an HTML form to a PHP script for storage in a database. The script should also handle error messages if the user inputs an invalid email address. I want to make this process ...

Is it possible that the rotation of multiple images using jquery in php is not functioning properly?

Is there a way to display images using PHP and rotate them using canvas and jQuery? The issue arises when showing more than one image as the rotation fails. I suspect the problem lies in the image or canvas ID in the JavaScript code, but I'm unable to ...

Execute the script repeatedly

(Since Stack snippet is temporarily down, I included a jsfiddle link): Visit this link for the code I've been struggling to get this script to work. Here's the simple Javascript code I have: $(document).ready(function() { showMessage(); s ...

Utilizing JavaScript regex to remove substrings that contain parentheses

I am working with a string variable named myString that includes some unwanted content towards the end: var myString = 'The sentence is good up to here foo (bar1 bar2)'; var toBeRemoved = 'foo (bar1 bar2)'; I am looking for the best w ...

What is the best way to extract all values from an array that meet a specific condition?

I have an array structured like the following and I'm looking to retrieve all values where the description matches a given value. I understand how to retrieve the first array value where the condition is met, but I'm unsure of how to retrieve all ...

Retrieving Data Dynamically from a MEAN Stack Database Using Variables

I need to fetch data from MongoDB that matches a specific userId. Say I have the following data stored in the database: { "_id": "hjdhs88889dsijd8", "items": "xxxxxx", "userId": "A123" }, { "_id": "hjhuf77889dsijd8", "items": "xxxxxx", ...

Issue encountered while retrieving JWT

Currently, I am tackling the challenge of implementing JWT authentication using Angular and Java Jersey. I have successfully managed to send the JWT token from the server to the client, which can be observed as a POST response with a status code of 200 in ...

Issue with deleting and updating users in a Koa application

My goal is to create a function that deletes a specific user based on their ID, but the issue I'm facing is that it ends up deleting all users in the list. When I send a GET request using Postman, it returns an empty array. What am I doing wrong? I do ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...

When is the appropriate time to provide arguments to the constructor of a TypeScript service?

I am grappling with the concept of when to pass arguments to a service's constructor versus passing them in the execution of the service. For instance, I have a service that filters rows from an Excel sheet: @Injectable() export class FilterRowsServi ...

Sending data to Layout for customizable routes (App Router) in Next.js version 13

Looking to pass props to the Layout component for dynamic routes in my project structure: /app -/(site) --/layout.tsx --/page.tsx --/[slug]/page.tsx --/[slug]/layout.tsx In the site layout: export default async function IndexRoute({ children }: { chil ...