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

The leaflet.js library threw an error: LatLng object is not valid due to invalid coordinates (NaN, NaN)

Currently, I am working with a JSON file that contains coordinates in pairs. "_id" : ObjectId("59407457838b932e0677999e"), "type" : "MultiPoint", "name" : "points", "coordinates" : [ [ -73.958, 40.8003 ], ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

What is the best way to combine multiple JSON files containing website metadata into a single JSON file for exploratory data analysis using Python?

In my current project, I am faced with the task of organizing 2 folders filled with a mix of JSON files and corresponding audio recordings (approximately 400 JSON files). Here is an example of what the data looks like: { "id":"c79c32e7-6665-4c5e-9458-d1 ...

Having trouble with implementing a 64-bit bitwise AND operation in JavaScript?

I've been attempting to perform a bitwise AND operation on long numbers using Javascript. Despite trying the solutions provided at (How to do bitwise AND in javascript on variables that are longer than 32 bit?), none of them have been accurate for the ...

Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)? I've been attempting to do so with this code: var call = { "filterParameters": { "id": 18855843, "isInStockOnly": false, "newsOn ...

Creating a nested list component using an array of objects

Seeking guidance for a coding task I recently completed. I was tasked with creating a multiple nested list from an array of objects. While I achieved the expected result, my code ended up being overly complicated and not very clean. I used a combination of ...

Whenever a user logs in or logs out from the child component, the app.js is not being re-rendered

I'm having trouble figuring out how to re-render the app.js function. It loads initially, but when I click the login or logout button, I need to call a function from the helper again to check the user status. Here is the code snippet for App.js: impor ...

What is the best way to transform a JSON array into a string?

Is there a way to convert an array into a string using php? Check out the sample array below: { "result": "success", "message": [ { "date_insert": "2017-01-28 20:14:51", "date_update": "2017-01-28 20:15:11", ...

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

Using Class-based CreateView to return a JsonResponse

I am currently utilizing curl to send form data to my website. curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8f939199a39a959099c1bc9a959099d2888488">[email protected]</a> -F name=test_01 https://localho ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...

Having difficulty organizing the Dgrid

var CustomGrid = declare([Grid, Keyboard, Selection]); var questionGrid = new CustomGrid({ store: questionCacheStore, columns: [ editor({ ...

Discovering the key and corresponding value within a JSON object based on a different key-value pair

I am currently working in PostgreSQL and I'm attempting to extract the key (r_dirigeant, r_actionnaire, r_beneficiaire) or generate a text containing all keys when "r_ppe" = "oui" and one of the keys (r_dirigeant, r_actionnaire, r_beneficiaire) is als ...

Vue (Gridsome) App encountering 'Cannot POST /' error due to Netlify Forms blocking redirect functionality

Currently, I am in the process of developing my personal website using Gridsome. My goal is to incorporate a newsletter signup form through Netlify Forms without redirecting the user upon clicking 'Submit'. To achieve this, I utilize @submit.prev ...

Failed to perform the action using the Angular Post method

Currently, I am exploring the use of Angular with Struts, and I have limited experience with Angular. In my controller (Controller.js), I am utilizing a post method to invoke the action class (CartAction). Despite not encountering any errors while trigge ...

Transmit the bound data (using ng-model) to a custom AngularJS directive

/*I am looking to define the maxDate as vmEndDate*/ app.directive('myDatepicker', function ($parse) { return function (scope, element, attrs, controller) { var ngModel = $parse(attrs.ngModel); alert(element.va ...

What is the best way to iterate through indexed numbers within a stdClass Object?

The desired output that I am attempting to access is as follows: stdClass Object ( [results] => stdClass Object ( [columns] => stdClass Object ( [name] => Name [id] => ...

Improving the efficiency of rendering multiple objects on a canvas

I'm currently working on developing a simulation for ants using the basic Javascript canvas renderer. Here is a snippet of the rendering code: render(simulation) { let ctx = this.ctx; // Clearing previous frame ctx.clearRect(0, ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...