skip to Main Content

I got array:

const DATA_Section = [
  {
    id: 0,
    text: "Some text1",
  },
  {
    id: 1,
    text: "Some text2",
  },
  {
    id: 2,
    text: "Some text 3",
  },
];

and I want to use text from this array to create dynamic component. Idea is: I can see text[0], I click some button then I can see text[1], something like loop. How can to do it?

2

Answers


  1. You can do this way maybe.

    const DATA_Section = [
      {
        id: 0,
        text: "Some text1",
      },
      {
        id: 1,
        text: "Some text2",
      },
      {
        id: 2,
        text: "Some text 3",
      },
    ];
    
    const Component: FC = () => {
      const [initialRenderState, setInitialRenderState] = 
      useState(DATA_Section[0])
    
      return (
        <View>
          {intialRenderState.map(item => <Text key={item.id}>{item.text}</Text>)}
          <Pressable onPress={()=> setInitialRenderState(prevState => [...prevState, Data_Section[prevState.length]])}>
            <Text>Add item</Text>
          <Pressable>
        </View>
    
      )
    }
    
    
    Login or Signup to reply.
  2. const DATA_Section = [
    {
      id: 0,
      text: "Some text1",
    },
    {
      id: 1,
      text: "Some text2",
    },
    {
      id: 2,
      text: "Some text 3",
    },
    ];
    
    const sample = () => {
    
      const [ index, setIndex ] = useState(0);
    
      const handleChangeIndex = () => {
      if (index < DATA_Section.length) {
      setIndex(index + 1);
      }else{
      setIndex(0);
      }
      }
    return(
    <View style={{flex:1}}>
    <TouchableWithoutFeedback onPress={()=>handleChangeIndex()}>
    <View style={{width:100, height:50, backgroundColor:'red'}}>
    <Text>
    {DATA_Section[index].text}
    </Text>
    </View>
    </TouchableWithoutFeedback>
    </View>
    );
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search