How to display a default value on a page in react Native - react-native

I am displaying content on the page on click of a drop-down button. I want to set some default value on the page irrespective of the dropdown button click and it should change when clicked on the drop-down button. Is there any way of doing it. Please Help.
My dropdown has 4 items. I want to display the first item as default. I have written an onclick event for it and for every onclick, I am fetching a service.
async onChangeText(apiurl) {
this.setState({
refreshing: false
});
let paramUrl;
this.state.data.forEach(eachUrl => {
if (apiurl === eachUrl.displayName) {
paramUrl = eachUrl.apiurl;
}
});
const res = await getResult(paramUrl);
this.setState({ listItems: res.data });
}
My dropdown looks like this
<Dropdown
data={this.state.data}
label='Select'
fontSize={15}
valueExtractor={({ displayName }) => displayName}
itemPadding={10}
onChangeText={this.onChangeText.bind(this)}
/>

Related

Updating nested state in React Native when mapping over data

I am mapping over state which displays 3 radio buttons and I only want 1 out of the 3 to be selected at one time and show the selected radio button style - so just a standard behaviour.
The first radio button - isChecked is defaulted to true and I then want to be able to switch the selected styles onPress of the other radio buttons which displays an inner filled circle.
I am getting confused on how to handle the isChecked as true for only the selected Radio Button onPress. I believe I should be using the index of the map to update the state but im unsure on how to go about it.
const [option, setOption] = useState([
{ permission: 'Standard User', isChecked: true },
{ permission: 'Approver', isChecked: false },
{ permission: 'Administrator', isChecked: false },
]);
const RadioButton = ({ checked, onCheck }) => (
<StyledRadioButton onPress={onCheck}>
{checked && <SelectedRadioButton />}
</StyledRadioButton>
);
{option.map(({ isChecked }, i) => (
<RadioButton
onCheck={() =>
setOption(
...prev => {
!prev.isChecked;
},
)
}
checked={isChecked}
/>
))}
Your state is an array of objects which hold a boolean flag. If the user checks a checkbox, then this flag should be set to true while all the others should be set to false. The setter of the state receives an array again, thus we could use the map function again as well as the index argument as you have suggested yourself in your question.
{option.map(({ isChecked }, i) => (
<RadioButton
onCheck={() =>
setOption(
prev => prev.map((opt, index) => ({...opt, isChecked: i === index ? true : false}))
)
}
checked={isChecked}
/>
))}

How to show the index and end of the Flatlist by 15 items on every click

I need to show the index and bottom of the list while click on the up and down button.
Is any option to show only 15 items up or down If I click on the up or down arrow.
For Eg) Consider a list has 500 items. It has an up and down arrow. If I click on the down arrow once I need to show only 15 items for the first time and If click on the down arrow next need to show the next 15 items.
Also If I click on the up arrow it needs to show 15 items above not all
In this usecase I need to move up and down of the screen. Any option to modify the scrollToIndex and scrollToEnd in Flatlist to achieve this use case
upButtonHandler = () => {
//OnCLick of Up button we scrolled the list to top
this.ListView_Ref.scrollToOffset({ offset: 0, animated: true });
};
downButtonHandler = () => {
//OnCLick of down button we scrolled the list to bottom
this.ListView_Ref.scrollToEnd({ animated: true });
};
<TouchableOpacity
activeOpacity={0.5}
onPress={this.downButtonHandler}
style={styles.downButton}>
<Image
source={{uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_down.png',
}}
style={styles.downButtonImage}
/>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.5}
onPress={this.upButtonHandler}
style={styles.upButton}>
<Image
source={{uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_up.png',
}}
style={styles.upButtonImage}
/>
</TouchableOpacity>
You can slice the data provided to the FlatList every time a button is pressed.As the FlatList is a pure Component you need to pass a extra prop to re render the FlatList after button is pressed
Maintain a state variable such as section which describes which part of data to display like (0,15),(15,30),...
Update this variable inside the up and down buttons,taking care of the boundaries so as not to get bad results.This is easily solved by wrapping setState inside a if condition so it will look roughly as
updateSectionLow = () => {
const { section } = this.state;
if (section > 0) {
this.setState({
section: section - 1,
});
}
};
updateSectionHigh = () => {
const { section, data } = this.state;
if (data.length > (section + 1) * 15) {
this.setState({
section: section + 1,
});
}
};
and the FlatList looks like this
<FlatList
data={this.state.data.slice(this.state.section*15,(this.state.section+1)*15)}
renderItem={({ item }) => {
return (
<View style={styles.row}>
<Text>{item.data}</Text>
</View>
);
}}
extraData={this.state.section}
/>
Here is a working expo demo
EDIT
After having discussion with the OP person,i have changed my code little bit.
Get the offset after scroll,
for a vertical list
onMomentumScrollEnd={e => this.scroll(e.nativeEvent.contentOffset)}
Inside the handler
this.setState({
index: Math.floor(offset.y / (ITEM_HEIGHT+SEPARATOR_HEIGHT)),
});
if there is no separator then you can put SEPARATOR_HEIGHT to be 0
and it is only matter of using scrollToOffset with ref as follows
for going down the list by ITEMS_DISP(like 15)
this.flatListRef.scrollToOffset({
offset:(this.state.index+ITEMS_DISP)*ITEM_HEIGHT+(this.state.index+ITEMS_DISP)*SEPARATOR_HEIGHT
});
for going top the list by some ITEMS_DISP
this.flatListRef.scrollToOffset({
offset:(this.state.index-ITEMS_DISP)*ITEM_HEIGHT+(this.state.index-ITEMS_DISP)*SEPARATOR_HEIGHT
});
Updated demo link

How to change styling of input clear button?

I'm working with a React Native form input field and would like to change the color and positioning of the clear button. The default clear button is too close in color to my background color.
<FloatingLabel
clearButtonMode={'always'}
style={styles.floatStyle}
inputStyle={styles.floatInput}
value={this.state.formData.email}
keyboardType={'email-address'}
autoCapitalize={'none'}
onChangeText={(value) => {
this.setState({
formData: {
...this.state.formData,
email: value
}
})
}}>Email</FloatingLabel>

Receiving wrong params when navigating to a route

I'm using react-navigation in my react native app.
In two different places I a have button to navigate to a route. One button also sends params and one button does not:
<Button onPress={() => { navigation.navigate('profile', { user: 'test' }) }} title="test" />
<Button onPress={() => { navigation.navigate('profile') }} title="test" />
In profile route I have a componentWillMount function to set state according to received params:
componentWillMount() {
const { params } = this.props.navigation.state;
if (params && params.hasOwnProperty('profile')) {
this.setState({
profile: params.profile
});
}
}
The problem is that if I press the first button (the one that sends params), then navigate back to the same view and press the second button, I'm still receiving the same params, even though the second button isn't sending any!
Not by my computer so I can't test.
But what if you navigate with the second button first? Do you still get the params passed to the page?
Also you dont mention what type navigation you sre navigating to. A stack, drawer or tab. Add some more info and I'll try to come back to you tomorrow.
But my impression is that you are navigating to the same page the second time and that page is already mounted. And hence not rerendered. Have you tried with componentDidUpdate an passing no variables on the second button?
This is the change I suggest in our discussion:
if (params && params.hasOwnProperty('profile')) {
this.setState({
profile: params.profile
});
else if (params && params.hasOwnProperty('profile')){
this.setState({
profile: null
});
}

how to close modal popup when browser back button is clicked in vuejs?

We make use of modal component from https://github.com/yuche/vue-strap. When browser back button is clicked, the default behavior is back to previous path but the modal popup isn't closed. How can I change the behavior to close the modal popup upon browser's back button click event?
This helped me.
https://jessarcher.com/blog/closing-modals-with-the-back-button-in-a-vue-spa/
created() {
const backButtonRouteGuard = this.$router.beforeEach((to, from, next) => {
if (from.name == 'menu') {
/* Blocking back button in menu route */
next(false);
this.yourCallBackMethod()
} else {
/* allowing all other routes*/
next(true);
}
});
this.$once('hook:destroyed', () => {
backButtonRouteGuard();
});
},
methods: {
yourCallBackMethod() {
// Go to the previous step, or close the modal
}
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>