display a screen based on conditions using conditional rendering techniques

As I work on the onboarding screen, my goal is to navigate to a different screen when the last item is displayed or clicked instead of just logging "last item" on the console. Here's the code snippet:

 import React,{useState,useRef} from 'react';
    import { View, Text,StyleSheet, FlatList, Animated } from 'react-native';
    
    import OnboardingItem from "./OnboardingItem";
    import slides from "./slides"
    import Paginator from './Paginator';
    import NextButton from './NextButton';
    import WelcomeScreen from "../../screens/WelcomeScreen"
    
    
    export default Onboarding  =  () => {
      const [currentIndex,setCurrentIndex] = useState(0);
    
      const scrollX = useRef(new Animated.Value(0)).current;
    
      const slidesRef = useRef(null);
    
      const viewableItemsChanged = useRef(({viewableItems}) =>{
        setCurrentIndex(viewableItems[0].index );
      }).current;
    
      const viewConfig = useRef({ viewAreaCoveragePercentThreshold:50 }).current;
    
      const scrollTo = () => {
        if(currentIndex < slides.length - 1){
          slidesRef.current.scrollToIndex({index: currentIndex + 1})
        }else{
           console.log("last item");
        }
      }
    
      return (
        <View style={styles.container}>
          <View style={{flex:3}}>
          <FlatList 
          data={slides} 
          renderItem={({item}) => <OnboardingItem item={item} /> } 
          horizontal
          showsHorizontalScrollIndicator={false}
          pagingEnabled
          bounces={false}
          keyExtractor={(item) => item.id }
          onScroll={Animated.event([{nativeEvent: {contentOffset:{x:scrollX} } }],{
            useNativeDriver:false,
          })}
          scrollEventThrottle={32}
          onViewableItemsChanged={viewableItemsChanged}
          viewabilityConfig={viewConfig}
          ref={slidesRef}
          />
          </View>
          <Paginator data={slides} scrollX={scrollX} />
          <NextButton scrollTo={scrollTo} percentage={(currentIndex + 1 ) * (100/slides.length)} />
        </View>
      )
    };
    
    const styles = StyleSheet.create({
        container:{
          flex:1,
          justifyContent:"center",
          alignItems:"center"
        }
    })

Here is the navigation setup which includes the Welcome Screen:

import React from "react";
import { createNativeStackNavigator } from '@react-navigation/native-stack';


import LoginScreen from "../screens/LoginScreen";
import RegisterScreen from "../screens/RegisterScreen";
import WelcomeScreen from "../screens/WelcomeScreen";
import Onboarding from "../components/Getstarted/Onboarding"

const Stack = createNativeStackNavigator();

const AuthNavigator = () => (
  <Stack.Navigator>
    <Stack.Screen
      name="Welcome"
      component={WelcomeScreen}
      options={{ headerShown: false }}
    />
    <Stack.Screen name="Login" component={LoginScreen} />
    <Stack.Screen name="Register" component={RegisterScreen} />
  </Stack.Navigator>
);

export default AuthNavigator;

Despite considerable effort, I am facing difficulties navigating properly within my project. Any assistance with resolving this issue would be greatly appreciated.

Answer №1

When utilizing the function Onboarding, it expects two arguments: route and navigation. These can be used for navigating to different screens.

export function Onboarding({
  route,
  navigation
}) {
  // .. rest of the code
  if () {

  } else {
    navigation.navigate('NameOfScreen', {
      // options
    })
  }
}

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

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Best Practices for Handling an Abundance of Data in React or Java

I am facing a challenge with my project setup, where I have the front end in ReactJS and the backend API in Spring Boot. The task at hand is to display a drop down list filled with records retrieved from the API. Here's the scenario: I receive a list ...

Sidebar-driven top navigation menu

I am currently developing a Single Page Application using VueJS along with vuerouter. In my App.vue file, the structure is as follows: <template> <div id="app"> <header><topbar></topbar></header> <div cl ...

Transitioning from traditional Three.js written in vanilla JavaScript to React Three Fiber involves a shift in

I am currently faced with the task of converting a vanilla JS Three.js script to React Three Fiber. import * as THREE from 'three'; let scene, camera, renderer; //Canvas const canvas = document.querySelector('canvas') //Number of lin ...

A guide to retrieving nested values from a JSON object using JavaScript

Having trouble accessing specific values from a heavily nested JSON content returned by a URL? You're not alone! Many tutorials only cover simple nesting examples. Take a look at the code snippet I've been working on: $(document).ready(function ...

When using Nuxt JS and Jest, a warning message may appear stating "[Vue warn]: Invalid Component definition" when importing an SVG file

I am facing a unique issue only in my Jest unit test where an error occurs when I import an SVG into the component being tested: console.error node_modules/vue/dist/vue.common.dev.js:630 [Vue warn]: Invalid Component definition: found in -- ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Develop a radio button filter utilizing the "Date of Creation" attribute, implemented with either jquery or JavaScript

I am currently utilizing a customized Content Query Web Part to load a series of list items. Each of these items has an XSLT attribute known as the Created Date. Shown below is an example of the markup: <div class="item" createddate="2014-01-22 13:02 ...

Design your very own personalized WebView

I am looking to streamline the WebView usage in my program by creating a custom WebView with all the necessary settings. Currently, I am experiencing a situation where the WebView is not displaying anything, although there are no errors being reported. Cou ...

Reduce the number of divs on a webpage while incorporating animated transitions

I've been attempting to incorporate an animation on the width property for my div .panels. I've tried using transition-property in CSS and also with .animate() in jQuery, but unfortunately, it doesn't seem to be working. I also noticed that ...

Displaying a cordova camera plugin captured photo within the IMG element

Seeking assistance with the Apache Cordova Camera API to display camera-retrieved images. I am able to capture the image, and the file URL looks like: file:///mnt/.....something.jpg However, I am encountering difficulty setting this image in an existing ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

Obtaining a URL in JavaScript

Hey there, I'm diving into the world of JavaScript and could use some guidance. I'm currently working on implementing forward and backward buttons on a webpage. The URL structure is http://webaddress.com/details?id=27 My goal is to write two fun ...

Is it necessary to create event objects before setting event handlers in Leaflet JS?

I'm currently working on creating event handlers that respond to the success of the location() method in the leaflet JavaScript map class Here is my current implementation: function initializeMap() { var map = L.map('map').locate({setV ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

"Need to remove all chosen selections within an ng-repeat loop? Here's how

var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.cars = [{ model: "Ford Mustang", color: "red" }, { model: "Fiat 500", color: "white" }, { model: " ...

Action bar with a FloatingActionButton overlay

Is it possible to place a floatingActionButton on top of an actionBar? If so, how can it be accomplished? Below is the current XML code: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout ...

Utilizing Cordova and AngularJS to efficiently retrieve JSON data through XMLHttpRequest in a factory

I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response. Below is the code for ...