Adding a button in a FlatList in React Native - react-native

I have a FlatList and I am trying to but a button below the items and when you click on the button it should display the name of the item in an alert.
class TopMovies extends React.Component {
constructor(props) {
super(props);
this.state = {
apiTopLoaded: false,
topPopularMovies: [],
}
this.conditionalTopPopular = this.conditionalTopPopular.bind(this);
this.mybuttonclick = this.mybuttonclick.bind(this);
}
componentDidMount() {
fetch('someurls')
.then((response)=>{
response.json()
.then((popularMovies) => {
this.setState({
apiTopLoaded: true,
topPopularMovies: popularMovies.results,
})
})
})
mybuttonclick() {
Alert.alert(item.original_title)
}
conditionalTopPopular() {
if(this.state.apiTopLoaded===true) {
return(
<FlatList
horizontal={true}
data={this.state.topPopularMovies}
renderItem={({ item }) => (
<View>
<Text>{item.original_title}</Text>
<Button onPress={this.mybuttonclick} title="hello"/>
</View>
)}
keyExtractor={item => item.id}
/>
</View>
)
}
}
I can see all the movie names in the list and I see buttons below the movie names, but when I click on it, it says "cant find variable item". The function mybuttonclick should alert the item.original_title prop because it displays correctly in the flatlist. Please help.

Change your function like this:
mybuttonclick(movieTitle) {
Alert.alert(movieTitle)
}
And pass in the the movie title like this:
<Button onPress={this.mybuttonclick(item.original_title)} title="hello"/>

You should use the fat arrow function in the onPress like this.
<Button onPress={() => this.mybuttonclick(item.original_title)} title="hello"/>

Related

Get user input from input field in react similar to getElementById in react native using props

I am doing a loan calculation app and i run into the trouble since i am new to react native and previously i have been manipulating the DOM using querySelector or getElementById functions. However this does not work in react, and i am using state to store the value from the user, but i just can't seem to get it right, What am i doing wrong?
I've inserted the calculation element that is later rendered in app.js. All elements are showing up with no error, but the problem is to get user input data and then be able to use that data and do calculations.
Here is my Class
class LanKalkylElement extends React.Component {
constructor(props) {
super(props);
this.state = {
loanAmount: 20000,
loanInterest: 2.5,
loanYear: 10,
};
}
changeAmount(loanAmount) {
this.setState(() => {
return {
loanAmount: parseFloat(loanAmount),
};
});
}
changeInterest(loanInterest) {
this.setState(() => {
return {
loanInterest: parseFloat(loanInterest),
};
});
}
changeYear(loanYear) {
this.setState(() => {
return {
loanYear: parseFloat(loanYear),
};
});
}
calcButton() {
Alert.alert(this.props.loanAmount);
}
buttonHomeFunc() {
this.props.navigation.navigate('Start');
}
render() {
const {loanAmount, loanInterest, loanYear} = this.state;
return(
<View style={styles.contentStyle}>
<Text style={styles.text}> Lånebelopp </Text>
<TextInput style={styles.numericInput}
onBlur={Keyboard.dismiss}
keyboardType={'numeric'}
value={loanAmount}
onValueChange={this.changeAmount.bind(this)} />
<Text style={styles.text}> Ränta </Text>
<TextInput style={styles.numericInput}
onBlur={Keyboard.dismiss}
keyboardType={'numeric'}
value={loanInterest}
onValueChange={this.changeInterest.bind(this)} />
<Text style={styles.text}> Antal år: {String(loanYear)}</Text>
<Slider step={1}
maximumValue={15}
value={loanYear}
onValueChange={this.changeYear.bind(this)} />
<Button title='Kalkylera' onPress={() => this.calcButton()}/>
<Text style={styles.textResult}>Total summa att återbetala:</Text>
<Text style={styles.textResult}>varav räntekostnad:</Text>
<Button title='Tillbaka' onPress={() => this.buttonHomeFunc()}/>
</View>
)
}
}
export default withNavigation(LanKalkylElement);
When a user changes a value in a text input, onValueChange is called. You have bound this prop to functions that modify the state for this component.
This means the value in the text input will always match the value in the state. Therefore, if you need to access the value in a text input you would simply retrieve it from the state, like this:
const loanAmount = this.state.loanAmount;
doSomethingWithLoanAmount(loanAmount);

React native updates state "on its own"

I have two screens, one list (Flatlist) and one filter screen where I want to be able to set some filters for the list. the list screen has the states "data" and "usedFilters". When I am switching to the filters screen, the states are set as navigation parameters for react navigation and then passed via navigation.navigate, together with the onChange function, as props to the filter screen. There they are read, and the filters screen class' state is set (usually with passed filters from the list screen, if no valid filters has been passed, some are initialized).
After that the filters can be changed. If that happens, the state of the filter screen gets updated.
If then the apply button is clicked the filter screens' state is passed to the onChange function and via that back to the list screen, the onChange function updates the state "usedFilters" state of the list screen. If the cancel button is pressed null is passed to the onChange function and there is no setState call.
Setting new states for the list screen works perfectly fine. the problem is, that when i press the cancel button (or the back button automatically rendered by react navigation) the changes are kept nevertheless. That only happens if the state has been changed before. So if there has never been applied a change and hence the "usedFitlers" state of the list screen is null, this behavior does not occur. Only if I already made some changes and hence the "usedFitlers" state of the list screen has a valid value which is passed to the filters screen the cancel or go back buttons won't work as expected.
I am using expo-cli 3 and tried on my android smartphone as well as the iOS simulator. Same behavior. I looked into it with chrome dev tools as well but i simply couldn't figure out where the "usedFitlers" state was updated.
I am using react native 0.60 and react navigation 3.11.0
My best guess is that for some reason the two states share the same memory or one is pointer to the other or sth like that. (Had problems like that with python some time ago, not knowing the it uses pointers when assigning variables).
Anyone got an idea?
List Screen:
export default class ListScreen extends React.Component {
state = { data: [], usedFilters: null };
static navigationOptions = ({ navigation }) => {
let data = navigation.getParam('data')
let changefilter = navigation.getParam('changeFilter')
let currfilter = navigation.getParam('currFilter')
return {
headerTitle:
<Text style={Styles.headerTitle}>{strings('List')}</Text>,
headerRight: (
<TouchableOpacity
onPress={() => navigation.navigate('FilterScreen', {
dataset: data, onChange: changefilter, activeFilters:
currfilter })} >
<View paddingRight={16}>
<Icon name="settings" size={24} color=
{Colors.headerTintColor} />
</View>
</TouchableOpacity>
),
};
};
_onChangeFilter = (newFilter) => {
if (newFilter) {
this.setState({ usedFilters: newFilter })
this.props.navigation.setParams({ currFilter: newFilter });
} // added for debugging reasons
else {
this.forceUpdate();
let a = this.state.usedFilters;
}
}
_fetchData() {
this.setState({ data: fakedata.results },
() => this.props.navigation.setParams({ data: fakedata.results,
changeFilter: this._onChangeFilter }));
}
componentDidMount() {
this._fetchData();
}
render() {
return (
<ScrollView>
<FlatList/>
// Just data rendering, no problems here
</ScrollView>
);
}
}
Filter Screen:
export default class FilterScreen extends React.Component {
static navigationOptions = () => {
return {
headerTitle: <Text style={Styles.headerTitle}> {strings('filter')}
</Text>
};
};
state = { currentFilters: null }
_onChange = (filter, idx) => {
let tmp = this.state.currentFilters;
tmp[idx] = filter;
this.setState({ currentFilters: tmp })
}
_initFilterElems() {
const filters = this.props.navigation.getParam('activeFilters');
const dataset = this.props.navigation.getParam('dataset');
let filterA = [];
let filterB = [];
let filterC = [];
if (filters) {
// so some checks
} else {
// init filters
}
const filterElements = [filterA, filterB, filterC];
this.setState({ currentFilters: filterElements })
}
componentDidMount() {
this._initFilterElems()
}
render() {
const onChange = this.props.navigation.getParam('onChange');
return (
<ScrollView style={Styles.screenView}>
<FlatList
data={this.state.currentFilters} // Listeneinträge
keyExtractor={(item, index) => 'key' + index}
renderItem={({ item, index }) => (
<FilterCategory filter={item} name={filterNames[index]}
idx={index} onChange={this._onChange} />
)}
ItemSeparatorComponent={() => <View style=
{Styles.listSeperator} />}
/>
<View style={Layout.twoHorizontalButtons}>
<TouchableOpacity onPress={() => {
onChange(this.state.currentFilters);
this.setState({ currentFilters: null });
this.props.navigation.goBack();
}}>
<View style={Styles.smallButton}>
<Text style={Styles.buttonText}>{strings('apply')} </Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
onChange(null);
this.setState({ currentFilters: null });
this.props.navigation.goBack();
}}>
<View style={Styles.smallButton}>
<Text style={Styles.buttonText}>{strings('cancel')}
</Text>
</View>
</TouchableOpacity>
</View>
</ScrollView >
);
}
}
So when I press the cancel button, null is returned to the _onChangeFilter function of the list screen. This part works, and according to console.log and the debugger, the setState is not called. But if i set a breakpoint within the else part, i can see that this.state.usedFilters has changed.
Ok after a while i figured it out. The problem was that the whole filters list was always just referenced since react native (js) seems to always use references, even when changing sub-parts of the lists.
fixed that by using lodash cloneDeep.

React Native - Focus a TextInput (Inside custom Component) that is inside of a Flat List element

I'm a React Native beginner and I'm working with a Flat List and custom Rows. Inside of each custom row, I have elements like Text, TextInput, and Button. The problem is that I need to press one of these buttons that enables and triggers a focus to the TextInput.
I tried implementing that with refs but everything freezes so I don't know how to do that correctly.
My constructor
class EditProfileScreen extends React.Component {
constructor(props) {
super(props);
this._rowRefs = {}
}
My FlatList and MyCustomRow
_renderItem = ({item, index}) => {
return (
<MyCustomRow
fieldname={item.fieldname}
value={item.value}
isEditable={item.isEditable}
editFieldHandler={ this.editFieldHandler }
allowsEdition={item.allowsEdition}
ref={ref => { this._rowRefs[index] = ref}}
/>
)
}
_keyExtractor = (item, index) => index.toString();
render() {
return (
<View style={styles.mainContainer}>
<FlatList
ref={this.flatListRef}
style={styles.flatList}
data={this.state.fields}
renderItem={this._renderItem}
keyExtractor= {this._keyExtractor}
extraData={this.state.refresh}
/>
</View>
);
}
Trying to print the refs:
enableField(name) {
console.log('Printing refs...')
console.log(this._rowRefs) // the Button pressed freezes here
}
I expect to see what's inside of _rowRefs, but instead of that, the button just gets frozen and I never see that result in the console
Try to give the key for each ref (not index)
ref={ref => { this._rowRefs['key1'] = ref}}
and invoke focus action like this:
this._rowRefs['key1'].focus()
Can you try the above code after removing
console.log(this._rowRefs)

Where to trigger Modal-components in React Native?

I have a list of items in my app. When the user clicks on a list item I want to show more details in a . I could put the details-component into the list item component and hide it by default.
Is there a better way?
Assuming you will only be displaying a single Modal at a time. You can create the Modal component outside of the list and set it to visible on click of the list item. So you code will be something like this.
class YourComponent extends Component {
state = {
showModal: false,
};
render() {
const items = [1, 2, 3];
return (
<View>
<View>
{
items.map((item, i) => {
<Button key={i} onPress={() => this.setState({ showModal: true, item }) title="Open Modal" />
})
}
</View>
<ReactNative.Modal visible={this.state.showModal}>
<Text>{ this.state.item }</Text>
</ReactNative.Modal>
</View>
);
}
}

React native add active class when push the button

I have a 3 buttons on react native project iOS app. How can I set class active to clicked button and delete this class from others? Like addClass/removeClass that I had used on jquery?
First have your define your style "class".
const styles = StyleSheet.create({
btnSelected: {
...
},
notSelected : {
}
});
Then you can use a state property in your react component.
example :
state = {
btnSelected: 1
}
<Button
style={(this.state.btnSelected== 1)?styles.btnSelected:styles.notSelected}
onPress={() => this.setState({ btnSelected: 1 })} ... />
<Button
style={(this.state.btnSelected== 2)?styles.btnSelected:styles.notSelected} ...
onPress={() => this.setState({ btnSelected: 2 })} .../>
<Button
style={(this.state.btnSelected== 3)?styles.btnSelected:styles.notSelected}
onPress={() => this.setState({ btnSelected: 3 })} ... />
The key concept in React and React Native is, that you don't imperatively set the state of your UI. Instead, you change some state, and then declaratively render the UI based on that.
You could, for example use the local component state (this.state):
class Buttons extends React.Component {
state = {
activeButton: 'first'
}
render() {
return (
<View>
<Button
onPress={() => this.setState({ activeButton: 'first' })}
isActive={this.state.activeButton === 'first'}
/>
<Button
onPress={() => this.setState({ activeButton: 'second' })}
isActive={this.state.activeButton === 'second'}
/>
<Button
onPress={() => this.setState({ activeButton: 'third' })}
isActive={this.state.activeButton === 'third'}
/>
</View>
)
}
}
The onPress event handler sets local component state with setState, which causes the component to immediately re-render. The isActive property is then set on all the buttons based on the expression that compares this.state.activeButton with some value.