Customizing Dropdown Selections by Index in React Native

I am trying to achieve the functionality where each dropdown in the flatlist opens individually based on the index selected. For example, when you choose section 1, only that section should expand, while the others remain closed. Unfortunately, I have been unable to find a solution for this yet.

Below is the code snippet:

App.tsx:

// Code goes here

animate-height.tsx:

// Code goes here

If anyone can provide assistance or help me find a solution, it would be greatly appreciated. Thank you!

Answer №1

Give this a shot:

MainComponent.tsx

import React, { useState } from 'react';
import { View, Pressable, StyleSheet, Text, FlatList } from 'react-native';
import { AnimateHeight } from './animated-height';
import { Ionicons } from '@expo/vector-icons';
import { MotiView } from 'moti';
import Constants from 'expo-constants';

export default function MainComponent() {
  const questionsData = [
    {
      id: 1,
      question: "Are you a banana?",
      desc: "No, I am not.",
    },
     {
      id: 2,
      question: "Are you an apple?",
      desc: "Lorem Ipsum is simply dummy text of the printing and typesetting industry... etc.",
    },
  ]
  
  const [currentIndex, setCurrentIndex] = useState(0);
  const [showAnswers, toggleShowAnswers] = React.useReducer((show) => !show, false);

  const renderQuestionItem = ({item, index}:any) => {
    return(
    <View style={styles.screen}>
      <View style={styles.itemContainer}>
        <Pressable onPress={() => setCurrentIndex(index)} style={styles.questionContainer}>
          <Text selectable={false} style={styles.questionText}>
            {item?.question}
          </Text>
          <MotiView
            animate={{rotateZ: currentIndex == index ? '-90deg' : '0deg',}}>
              <Ionicons name="chevron-forward" color="white" size={17} />
          </MotiView>
        </Pressable>
        <AnimateHeight enterFrom="bottom" hide={currentIndex == index ? showAnswers : !showAnswers}>
          <View style={styles.answerContainer}>
            <Text style={styles.answerText}>
              {item?.desc}
            </Text>
          </View>
        </AnimateHeight>
      </View>
    </View>
    )
  }

  return (
    <View>
      <FlatList 
        data={questionsData}
        renderItem={renderQuestionItem}
        keyExtractor={(item)=> item.id.toString()}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    backgroundColor: '#161618',
    paddingTop: Constants.statusBarHeight,
  },
  itemContainer: {
    borderBottomWidth: 1,
    borderBottomColor: '#232326',
  },
  questionContainer: {
    padding: 16,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  answerContainer: {
    padding: 16,
    marginTop: -16
  },
  answerText: {
    color: '#A09FA5',
    lineHeight: 20
  },
  questionText: {
    color: '#EDEDEE',
    fontWeight: 'bold',
  },
});

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

Is it possible to combine two enums in TypeScript to create a single object with key-value pairs?

Incorporating two enums named Key and Label, as well as an interface called IOption, the goal is to generate an array of objects known as IOptions. const enum Key { Flag = 'flag', Checkbox = 'checkbox', Star = 'star&apo ...

Encountering Error 404 while submitting a form on Prisma, Axios, and NestJS

Currently, I am working on a Sign Up page using SolidJs and NestJS with Prisma. However, when I try to submit the form, I encounter an error that says POST 404 (Not Found) and this error is also returned by axios. Additionally, my setup includes postgres ...

Navigating states using redux and realm in a react-native environment

Currently, I am faced with the challenge of managing states and persisting states in a complex react-native application. My goal is to create a setup similar to Instagram, where posts are initially loaded into redux and then saved locally for offline viewi ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...

Children failing to load due to lazy loading implementation

Seeking help with a perplexing issue involving lazy-loaded modules. I have successfully implemented multiple lazy modules, except for the most recent one. This particular lazy module has been created with two children, but for some reason, the page is fail ...

Retrieve values of properties from an array

How can I retrieve property values from an array? const d = [{id: 'Cat'}, {id: 'Dog'}] type ids = ??? //place code here, type should be 'Cat' | 'Dog' (It would also be acceptable if it creates a const enum) ...

Function not being triggered by onClick event in React-Native application

Within my react-native mobile application, I have created a component named Row in the row.js file. This component includes a TouchableOpacity with an onClick() event handler. However, when this component is clicked, the associated function fails to execut ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Converting React useState to a JSON object data type

I imported a JSON data file using the following code: import data from "../data.json"; The contents of the file are as follows: [ { "name": "Emery", }, { "name": "Astrid", }, { " ...

If placed in the same document, will promises be executed sequentially?

Let's say I have a function in one file that returns a promise: public async a():Promise<string>{ return 'hi' } In another file, I use this function like so: await service.a.then( hi =>console.log(hi)).catch(err=>{throw err}); ...

Is it recommended to employ cluster connection within my Redis client when utilizing Azure Redis Cluster?

It seems that the Azure documentation on clustering can be a bit confusing. According to the docs: Will my client application need any modifications to support clustering? Once clustering is activated, only database 0 will be accessible. If your client ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

Having difficulty retrieving JSON data from a NodeJS server built with Typescript

My project involves using NodeJS + Express on the back end to send JSON data as a POST response to the front end through JQuery. I'm facing an issue where the message is not reaching the front end, which utilizes a JQuery AJAX call. It's puzzling ...

Obscure issue encountered during production: `Type Error: e is not defined`

After putting my Vue app into production, I encountered a perplexing issue with a specific component that throws an error message I can't track down. The problem seems to be related to the bundling process since it only occurs in production mode. Ste ...

Express TypeScript Error Handling Function

What are the different data types for the four parameters used in the error handling function in Typescript? app.use((err: ??, req: ??, res: ??, next: ??) => { }); While working in VS Code, I noticed red wiggly lines under all four parameters without ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

Create a Typescript React class and define the State type as either an interface or null

When working with React and typescript, it is common to declare state types in the following manner: import * as React from "react" interface IState { someState: string } class MyClass extends React.Component<{}, IState> { state = { someSt ...

Having trouble viewing the value of request headers in Firebase?

Here is my code snippet: var headers = new Headers(); headers.append("bunny", "test"); headers.append("rabbit", "jump"); fetch("blahurl.com/someservice", {headers:headers}) When it comes to handling the request on Firebase: export const listener = funct ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...