I want to implement a feature that changes the Valaszok style based on if it's selected or not and I want it to save the style so when I horizontally scroll through the flatlist, when I scroll back to it, it would still show it as selected and when I press EllenorzesButton it would behave the same. My problem is the style is not saved with my current implementation, how can I fix it? Please write down the whole code with comments where it changes something



import React, { useCallback, useEffect, useRef, useState} from 'react';
import { Dimensions, FlatList, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import Feladatok from "./Feladatok";
import { fetchAllData } from "../Database/Db";
import { Feladat } from '../Database/Feladat';
import { SafeAreaView } from 'react-native-safe-area-context';
import styles from './Teszt.style';
import { AntDesign as Icon } from '@expo/vector-icons';

const Darab = () => {
  const [feladatok, setFeladatok] = useState<Feladat[]>([]);
  const [ellenorizve, setEllenorizve] = useState<boolean>(false);
  const [answeredQuestions, setAnsweredQuestions] = useState<number[]>([]);
  const [index, setIndex] = useState(0);
  const { width: windowWidth } = Dimensions.get("window");
  const indexRef = useRef(index);
  indexRef.current = index;

  useEffect(() => {
    handleFetchFeladatok();
  }, []);

  const handleFetchFeladatok = () => {
    fetchAllData()
      .then((result) => {
        setFeladatok(result);
      })
      .catch((err) => {
        console.error("Error fetching feladatok: ", err);
      });
  };

  const ellenorzes = () => {
    setEllenorizve(true);
    setAnsweredQuestions((prevIndices) => [...prevIndices, index]);
  };

  const renderItem = ({ item, index }: { item: Feladat; index: number }) => {
      const isAnswered = answeredQuestions.includes(index);
      return <Feladatok feladat={item} ellenorizve={isAnswered} />;
    }

  const onScroll = useCallback((event: any) => {
    const slideSize = event.nativeEvent.layoutMeasurement.width;
    const index = event.nativeEvent.contentOffset.x / slideSize;
    const roundIndex = Math.round(index);

    const distance = Math.abs(roundIndex - index);

    const isNoMansLand = 0.4 < distance;

    if (roundIndex !== indexRef.current && !isNoMansLand) {
      setIndex(roundIndex);
      const currentPageAnswered = answeredQuestions.includes(roundIndex);
      setEllenorizve(currentPageAnswered);
    }
  }, [answeredQuestions]);

  const flatListOptimizationProps = {
    pagingEnabled: true,
    horizontal: true,
    initialNumToRender: 0,
    maxToRenderPerBatch: 3,
    scrollEventThrottle: 16,
    windowSize: 8,
    getItemLayout: useCallback(
      (_: any, index: number) => ({
        index,
        length: windowWidth,
        offset: index * windowWidth,
      }),
      [windowWidth]
    ),
  };

  return (
    <SafeAreaView style={styles.screen}>
      <FlatList
        keyExtractor={(item) => String(item.ID)}
        overScrollMode="never"
        data={feladatok}
        renderItem={renderItem}
        showsHorizontalScrollIndicator={false}
        onScroll={onScroll}
        {...flatListOptimizationProps}
      />
      <View style={styles.navContainer}>
        <View style={styles.navBar}>
          <View style={[styles.navBtnContainer, styles.prev]}>
            <TouchableOpacity style={styles.nextOrPrevBtn}>
              <Icon style={styles.nextOrPrevBtnIcon} name="leftcircle" size={50} color="#222222" />
            </TouchableOpacity>
          </View>
          <View style={styles.ellenorzesBtnContainer}>
            <TouchableOpacity
              style={!ellenorizve ? [styles.ellenorzesBtn, styles.activeBtn] : [styles.ellenorzesBtn, styles.inActiveBtn]}
              onPress={ellenorzes}
              disabled={ellenorizve}
            >
              <Text
                style={!ellenorizve ? [styles.ellenorzesBtnText, styles.activeText] : [styles.ellenorzesBtnText, styles.inActiveText]}
              >
                Ellenőrzés
              </Text>
            </TouchableOpacity>
          </View>
          <View style={[styles.navBtnContainer]}>
            <TouchableOpacity style={styles.nextOrPrevBtn}>
              <Icon style={styles.nextOrPrevBtnIcon} name="rightcircle" size={50} color="#222222" />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
};

export default Darab;


import React, { useCallback, useState } from 'react';
import { Text, View, Dimensions, StyleSheet } from 'react-native';
import { SvgXml } from 'react-native-svg';

import MathJax from './MathJax';
import styles from "./Teszt.style";
import ValaszokGroup from "./ValaszokGroup";
import { svgs } from '../../constants';
import { Feladat } from '../Database/Feladat';
import { ScrollView } from 'react-native';

//SplashScreen.preventAutoHideAsync();
interface FeladatokProps {
  feladat: Feladat;
  ellenorizve: boolean
}

const { width: windowWidth, height: windowHeight } = Dimensions.get("window");

const stylesDarab = StyleSheet.create({
  kerdesWrapper: {
    width: windowWidth,
  },
});

const Feladatok: React.FC<FeladatokProps> = ({ feladat, ellenorizve }) => {

  const [selectedValaszIndex, setSelectedValaszIndex] = useState<number>(-1);

  const handleSelection = useCallback((index: number) => {
    setSelectedValaszIndex(index);
  }, []);

    let svgValue : string | null = null;
    for (const [property, value] of Object.entries(svgs)) {
      if (property === feladat.Kerdes2) {
        svgValue = value.toString();
        break;
      }
    }

    return(
    <View key={feladat.ID} style={stylesDarab.kerdesWrapper}>
      <View>
        <View style={styles.feladatSzamTextContainer}>
          <Text style={styles.feladatSzamText}>{feladat.Feladatszam}.</Text>
        </View>
        <View style={styles.kerdesContainer}>
          <MathJax style={styles.kerdesMathJax} html={
          `<div class='kerdes'>${feladat.Kerdes}</div>`
          }/>
          {feladat.Kerdes2 && <SvgXml width={300} height={300} xml={svgValue}/>}
          {feladat.Kerdes3 && (
          <MathJax style={styles.kerdesMathJax} html={
            `<div class='kerdes'>${feladat.Kerdes3}</div>`
          }/>)}
        </View>
        
      </View>
      <ValaszokGroup
          key={feladat.ID}
          valasz={[feladat.Valasz1, feladat.Valasz2, feladat.Valasz3, feladat.Valasz4]}
          selectedIndex={selectedValaszIndex}
          onSelection={handleSelection}
          jo={feladat.Megoldas}
          ellenorizve={ellenorizve}
/>
    </View>
    );
  }

export default Feladatok

import React, { useState, useEffect } from "react";
import { StyleProp, View, ViewStyle } from 'react-native';

import styles from "./ValaszokGroup.style";
import Valaszok from "./Valaszok";

interface ValaszokGroupProps {
  valasz: string[];
  selectedIndex: number;
  onSelection: (index: number) => void;
  jo: number;
  ellenorizve: boolean;
}

const ValaszokGroup: React.FC<ValaszokGroupProps> = ({
  valasz,
  selectedIndex,
  onSelection,
  jo,
  ellenorizve,
}) => {
  const [selectedAnswerIndex, setSelectedAnswerIndex] = useState(selectedIndex);

  useEffect(() => {
    setSelectedAnswerIndex(selectedIndex);
  }, []);

  useEffect(() => {
    console.warn(selectedAnswerIndex);
  }, [selectedAnswerIndex]);

  const handleSelection = (index: number) => {
    setSelectedAnswerIndex(index);
    onSelection(index);
  };

  return (
    <View style={styles.container}>
      {valasz.map((object, i) => {
        const isSelected = selectedAnswerIndex === i;
        const itemStyle = isSelected ? styles.selected : styles.unSelected;

        return (
          <Valaszok
            key={"key" + i}
            valasz={object}
            jo={jo === i + 1}
            isSelected={isSelected}
            ellenorizve={ellenorizve}
            onSelection={() => handleSelection(i)}
            itemStyle={itemStyle}
          />
        );
      })}
    </View>
  );
}

export default ValaszokGroup;

import React from "react";
import { StyleProp, TouchableOpacity, ViewStyle } from 'react-native';
import MathJax from './MathJax';

import styles from "./Valaszok.style";

interface ValaszokProps {
  valasz: string;
  isSelected: boolean;
  onSelection: () => void;
  jo: boolean;
  ellenorizve: boolean;
  itemStyle: StyleProp<ViewStyle>; // New prop to hold the item style
}

const Valaszok: React.FC<ValaszokProps> = ({
  valasz,
  isSelected,
  onSelection,
  jo,
  ellenorizve,
  itemStyle,
}) => {
  return (
    <TouchableOpacity
      style={[styles.valaszButton, itemStyle]} // Apply the itemStyle here
      onPress={onSelection}
      disabled={ellenorizve}
    >
      <MathJax
        style={styles.valaszMathJax}
        html={`<span class='valasz' style='overflow: hidden; user-select: none; display: table; margin: 0 auto; font-size: 7vw;'>${valasz}</span>`}
      />
    </TouchableOpacity>
  );
}

export default Valaszok;