Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page.

import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true
    };
  }

  componentDidMount() {
    fetch('https://reactnative.dev/movies.json')
      .then((response) => response.json())
      .then((json) => {
        this.setState({ data: json.movies });
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }

  render() {
    const { data, isLoading } = this.state;

    return (
      <View style={{ flex: 1, padding: 24 }}>
        {isLoading ? <ActivityIndicator/> : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <TouchableOpacity>
                <Text>{item.title}</Text>
              </TouchableOpacity>
              
            )}
          />
        )}
      </View>
    );
  }
};

The code displays movie names as buttons that can be clicked individually. I am now interested in implementing separate pages for each button using react-native-router-flux.

{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{
"id": "1",
"title": "Star Wars",
"releaseYear": "1977"
},
{
"id": "2",
"title": "Back to the Future",
"releaseYear": "1985"
},
{
"id": "3",
"title": "The Matrix",
"releaseYear": "1999"
},
{
"id": "4",
"title": "Inception",
"releaseYear": "2010"
},
{
"id": "5",
"title": "Interstellar",
"releaseYear": "2014"
}
]
}

This JSON data contains the movie names retrieved through fetching. Perhaps utilizing the "id" field could assist me, but I'm unsure of the next steps.

Answer №1

My suggestion may be brief, but I believe it can help clarify things for you, especially considering the complexity of your question.

From my own experience, when using react-native-router-flux, you need to import your scene (page) and then use Actions.somepage() to navigate to that specific page. However, I found it challenging to achieve the same functionality with FlatList using

Actions.eachpage</code, possibly due to my skills not being advanced enough yet.</p>

<p>If you are aiming to accomplish what you described, my recommendation would be to create a new page component that handles all scenes, let's call it "HandlePage". You can then add it to your <code>TouchableOpacity
like this:

import HandlePage from "./HandlePage";
...
<TouchableOpacity onPress={() => { Actions.HandlePage({page: item.id}); }}

This way, you can control the rendering of pages in the HandlePage component by passing the parameter (id) to determine which page to render. By using a single Actions.HandlePage for navigation, you gain more flexibility in displaying the desired content.

I hope this explanation proves helpful.


Update:

An example implementation could look something like this:

import StarWars from "./StarWars";
import TheMatrix from "./TheMatrix";
import Inception from "./Inception";
import Interstellar from "./Interstellar";

export default class HandlePage extends React.Component {
  checkSwitch = param => {
    switch (param) {
      case "1":
        return <StarWars/>;
      case "2":
        return <TheMatrix recordCount = {this.state.recordCount}/>;

      case "3":
        return <Inception disabled = {this.state.disabled3}/>;

      case "4":
        return <Interstellar alert = {this.state.alert4}/>;

      default:
        return null;
    }
  };
  render() {
    return ({
      this.checkSwitch(this.props.page)
    });
  }
}

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

Stopping the loop: Disabling the SetInterval function with ResponsiveVoice code in JavaScript

Currently, I am developing a queuing system and implementing voice announcements using Responsive Voice. I have used setInterval, but the issue is that the voice keeps looping without stopping. $( document ).ready(function() { setInterval(function() ...

Video player for Angular 2

Hey there! I am currently exploring Angular 2 and attempting to create a video playlist feature. My goal is to showcase my favorite videos in a table layout, where clicking on a row will lead to the playback of the selected video. Right now, I am passing t ...

Modifying the JSON file to a different key while preserving the information contained in that specific section

Initially, I considered a straightforward search and replace of the JSON code underneath, examining it line by line. However, this method is not feasible as the same keyword may appear in multiple places, with only one specific line requiring modification. ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Issue: The content of the text does not align with the HTML generated by the server

I'm struggling with an algorithm in next.js and encountering hydration errors. Here is the code I am using: import numbers from "../../functions/numberGenerators.js" export default function test() { ...

Identify whether the final digit falls within the range of 1-4 or 5-9, and then apply styling to the corresponding

First, this is the structure of my table: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <table class="table group-9569" width="100%"> <tbody> <tr> <td class=" ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

Introducing a fresh Backbone object attribute that points to an existing instance property

While working with Backbone/Marionette, I came across something unusual. When I create a new instance of a view with a new collection property and then create another instance of the same view, it seems that the collection property of the second view point ...

What could be causing passport.authenticate to not be triggered?

After multiple attempts to solve my first question, I am still unable to find the answer. Maybe it's due to being a newbie mistake, but I've exhausted all my efforts. This is how I created the new local strategy for Passport: passport.use(new ...

Refreshing a webpage using AJAX from a different URL of a secondary web service

I am working on a page that retrieves data from a specific web service URL. I am conducting some processing involving a multiple choice checkbox, and I want the same page to reload and fetch its data from a second web service with a different URL to retrie ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Redirect to a specific webpage depending on a certain condition

I currently have a home page set up and now I would like to create a homePlus page that is controlled by a localStorage variable called alreadyShown. The concept is that once the homePlus page is shown for the first time, we will change the value of alread ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Hidden warning to React-select for being uncontrolled

I've integrated react-select into my code: import React, {Component} from 'react'; import Select, {createFilter} from 'react-select'; let _ = require('underscore') class Test extends Component { constructor(props) ...

Struggling to properly structure WCF JSON data for HighCharts integration?

I am having issues binding my WCF JSON data to HighCharts Pie. When I hardcode the data, it works fine but dynamic data processing does not seem to work. Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...

Converting HTML/Javascript codes for Android Application use in Eclipse: A Step-by-Step Guide

How can I implement this in Java? Here is the HTML: <head> <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="styles ...

The Django POST request is rejecting due to a missing or incorrect CSRF token, despite having included the token in the form

I'm encountering a 403 response when making a POST request despite including csrf_token in the data for an AJAX request. I made sure that csrf_token is not empty before sending the request, so everything seems correct. What could be causing this error ...

Manipulate HTML Elements with a Click of a Button in React

Is there a straightforward method to replicate this jQuery example using only React, without relying on jQuery or other external libraries? I'm still developing my ReactJS skills and hoping for guidance on dynamically creating and deleting elements. ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...