I'm a beginner in React Native ans struggling with adding Input (Search bars) into a list by clicking a button. Here's my code:
import React, { useState } from "react";
import {
View,
Text,
Button,
FlatList
} from 'react-native'
import InputDemo from '../components/InputDemo'
const INCREMENT = 1;
class AddInputDemo extends React.Component{
constructor(props){
super(props);
this.state={
counter: 0,
numOfInput: [0]
}
this.addInput = this.addInput.bind(this)
}
addInput(){
this.setState((state) => ({
counter: state.counter + INCREMENT,
numOfInput: [...state.numOfInput, state.counter]
}))
console.log(this.state.counter);
console.log(this.state.numOfInput);
}
render(){
return(
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<FlatList
data={this.state.numOfInput}
keyExtractor={(item, index) => item.id}
renderItem={itemData => {
<InputDemo/>
}}
/>
<Button title='Add a location' onPress={this.addInput} />
</View>
);
}
}
export default AddInputDemo;
Here's the InputDemo file:
import * as React from 'react'
import {
View,
Text,
TextInput,
Button
} from 'react-native'
const InputDemo = props => {
return(
<View style={{borderColor: 'black', borderWidth: 1}}>
<TextInput
placeholder='Search'
/>
</View>
)
}
export default InputDemo;
It's weird since I use this same logic with state in Functional Component. It works. But when applying to a Class Component, it does not show anything when I click that button.
THANKS FOR ANY HELP !!!
EDIT I tried to use extraData:
<FlatList
extraData={this.state.numOfInput}
keyExtractor={(item, index) => item.id}
renderItem={itemData => {
<InputDemo
id={itemData.item.id}
/>
}}
/>
And created an id for each InputDemo:
const InputDemo = props => {
return(
<View key={props.id} style={{borderColor: 'black', borderWidth: 1}}>
<TextInput
placeholder='Search'
/>
</View>
)
}
But it still does not work Please help !!!