Changing Visibility of a button inside the component dynamically - reactjs

I am using React-Navigation but I guess You don't really need to have a prior knowledge about it.
So I have a header Component which looks like this
const Header = (props) => {
return (
<View style={headerContainer}>
<View>
<Button onPress={() => props.navigation.navigate('Home')}
title="Go Back"/>
</View>
<Text style={header}> Knicx
<Text style={headerSecondary}> Crypto Ticker </Text>
</Text>
</View>
)
}
Now, In the above notice the button, Which I am currently showing on all the pages
<Button onPress={() => props.navigation.navigate('Home')}
title="Go Back"/>
But I don't want it to be there on some specific pages, like HomeScreen to say the least.
Now, One solution is to remove the <Header /> component in my homepage, Copy the above code snippet, past it in my HomeScreen and remove the Component ( sort of like hardcoding ) or two create two Header component, one with button and one without button
[Question:] But I was thinking if we could toggle the visibility of button dynamically or stack it on the top of <Header /> ? Can someone please tell me how can we do it? (No, We can set the opacity of the button to zero and change it whenever we need it)
[Update:] We can use redux to manage/pass the state but the problem is that in React-native we do not have display: none and I don't want to change use the opacity

Send showHomeButton: boolean as a prop to header
const Header = props => (
<View style={headerContainer}>
{this.props.showHomeButton && (
<View>
<Button onPress={() => props.navigation.navigate('Home')} title="Go Back" />
</View>
)}
<Text style={header}>
{' '}
Knicx
<Text style={headerSecondary}> Crypto Ticker </Text>
</Text>
</View>
);

Related

Hide picked items in a FlatList

I'm using react-native FlatList to render out a punch on elements the data of which comes from an external API.
I want to prevent the user from picking the same item twice. So the way I'm going about this it hiding the item after they pick it.
If, let's say, I have a state picked like so
const [ picked, setPicked ] = useState(false);
changing it will of course hide all the elements.
<FlatList
{/*some other props*/}
data={allCards}
renderItem={(card: ListRenderItemInfo<CardsProps>) => (
<TouchableOpacity
style={[ styles.holder, { display: picked ? "none" : "flex" } ]}
onPress={() => handleChoice(parseInt(card.item.id))}
>
<Card
{/*some card props*/}
/>
</TouchableOpacity>
)}
/>
How can I go about changing the state for only one element inside the FlatList??
Is there a better approach you would recommend to do the same job?
try it like this, it will work,
<FlatList
{/*some other props*/}
data={allCards}
renderItem={(card: ListRenderItemInfo<CardsProps>) => picked ? (
<TouchableOpacity
style={[ styles.holder, ]}
onPress={() => handleChoice(parseInt(card.item.id))}
>
<Card
{/*some card props*/}
/>
</TouchableOpacity>
): undefined}
/>
The easiest way to do this is if you create an object with all the ids and while inserting it you can check it whether it's in that list or not
it'll cost u O(1) time to check.
<FlatList
{/*some other props*/}
data={allCards}
renderItem={(card: ListRenderItemInfo<CardsProps>) => picked ? (
<TouchableOpacity
style={[ styles.holder, ]}
onPress={() => handleChoice(parseInt(card.item.id))}
>
<Card
{/*some card props*/}
/>
</TouchableOpacity>
): undefined}
/>
const map=new Map();
const handleChoice=(id)=>{
if(Map.get(id)===undefined){
Map.set(id,true)
//add the element to ur list where u need it to
}
}

Moving to Next Screen in react native

If i click on Lungs Banks i want to move to another screen How can i do this
<KeyboardAvoidingWrapper>
<WelcomeStyledContainer>
<StatusBar style="dark" />
<OrganHeading>
<OrganHeadingText>Donate Able Organ</OrganHeadingText>
</OrganHeading>
<View style={styles.container}>
<View style={styles.Box}>
<View style={styles.inerBox}>
<CardStyle>
<CardImage source={require('./../assets/organImage/lungs.png')} />
<CardText>Lungs Bank</CardText>
</CardStyle>
</View>
</View>
Below solution will work for you if you are using React-navigation.
UI Screen:
<CardText onPress={()=>navigation.navigate("YOUR SCREEN NAME HERE")}>Lungs Bank</CardText>
Card Text Component:
const CardText = ({onPress}) => {
return <Text onPress={onPress}>{props.children}</Text>;
}
Thanks!
You can use react-navigation
library to get started with navigation in react-native.

How to underline a specific word in a string for a React Native button

I'm using a Button component from react-native-elements and for the title prop I would like to underline one of the words, is this possible?
button.js:
<Button
buttonStyle={styles.buttonStyle}
titleStyle={styles.titleStyle}
containerStyle={styles.containerStyle}
title={title}
onPress={onPress}
disabled={disabled}
disabledStyle={[styles.disabledStyle]}
/>
I'm using it like this:
<Button
title={'First line \nSecond line'} // <- How to underline First & Second?
onPress={() => console.log('pressed button')}
/>
How do I underline the words First and Second?
I tried doing title={`${First} line \n${Second} line`} where First and Second is a <Text style={{textDecoration: 'underline}}>First</Text> but I'm getting [object, Object] since it's not an expression
<Button> implementation in React Native Elements indeed does support passing component as title property value - but in your code you try to pass those as text. That's what you might try instead:
const ButtonTitle = (
<>
<Text style={{textDecoration: 'underline'}}>First</Text>
<Text style={{textDecoration: 'underline'}}>Second</Text>
</>
)
<Button title={ButtonTitle} />
For situations like this, I generally will use React.ReactNode as the type for title instead of a string. This will be backwards-compatible, as strings are valid ReactNodes, but it also allows you to do this:
// style example
const style = Stylesheet.create({
underline: { textDecoration: 'underline' },
});
// Implementation in component
title={
<Text>
<Text style={style.underline}>
First line
</Text>
<Text style={style.underline}>
Second line
</Text>
</Text>
}
Reminder that the original will also still work as ReactNode is a type which includes string:
title={'First line \nSecond line'}

Implementing a counter in a React Native Flat List

Background
I'm building a screen for an app which displays a number of products brought from a firebase firestore collection. The way I display the products is via a FlatList, this is the code:
<FlatList
style={selected ? styles.visible : styles.hidden}
data={data}
renderItem={({ item }) => (
<View style={styles.container}>
<View style={styles.left}>
<Text style={styles.title}>{item.name}</Text>
<Text style={styles.description}>{item.description}</Text>
<Text style={styles.price}>${item.price}</Text>
<View style={styles.adder}>
<TouchableOpacity onPress={() => setCount(count - 1)}>
<Text style={styles.less}>-</Text>
</TouchableOpacity>
<Text style={styles.counter}>{count}</Text>
<TouchableOpacity onPress={() => setCount(count + 1)}>
<Text style={styles.more}>+</Text>
</TouchableOpacity>
</View>
</View>
<Image style={styles.right} source={{uri: item.image}}/>
</View>
)}
/>
Problem
As you can see, there's a counter in place for each item which the user can use to select how many units of the product they want to buy. The state is updated like this: const [count, setCount] = useState(0);
As you can see, this way of implementing the counter means that adding one unit of any product adds a unit of every product.
What I have tried
I've seen some people do this: setCount({counterA: 0, counterB: 0, etc.}) and update each counter, however as the number of products is always changing in the firebase document I can't hardcode the amount of counters I need.
Question
How can I edit my code so that it only affects the desired item?
The item in your renderItem function should be a separate component. In this separate component you will have a count that is scoped only to the component. So when the button is pressed on that component, only its count is incremented and not the others. The problem right now is you have one count that is on the parent component. After creating this new "counting" componenet, your FlatList will look something like:
<FlatList
style={selected ? styles.visible : styles.hidden}
data={data}
renderItem={({ item }) => (
<CountingComponent />
)}
/>

React Native, I can't tap without closing keyboard

Here is my phone screen I tried ScrollView with keyboardShouldPersistTaps, but it didn't work. I have a ScrollView for Autocomplete suggestions, and when user can types there, they should also be able to select from suggestions. However, without closing keyboard, it is not possible in my case. Here is my work
<ScrollView
scrollEnabled={false}
keyboardShouldPersistTaps={true}>
<View style={{ maxHeight: 220 }}>
<ScrollView style={Style.suggestionContainer}
scrollEnabled={true} >
{this.state.showOptions.map(this.renderSuggestions)}
</ScrollView>
</View>
</ScrollView>
.
.
.
private renderSuggestions(option: MultiInputQuestionOption) {
return (
<TouchableOpacity onPress={this.addSelection.bind(this, option)} >
<Text style={Style.suggestions}>
{option[this.props.titleKey]}
</Text>
</TouchableOpacity >
)
}
Is there any possible solution?
You need to pass the key keyboardShouldPersistTaps=‘handled’ on scroll view which contains the TextInput:-
<ScrollView keyboardShouldPersistTaps=‘handled’>
...
<TextInput />
</ScrollView>
And if you are having issue inside of a modal then You need to pass key keyboardShouldPersistTaps=‘handled’ on All scrollview which are in component stack for the screen. In the ancestors/parent of the Modal also.
Like in my case:
const CountryModal=(props)=>{
return(
<Modal
visible={props.visible}
transparent={false}
{...props}
>
<ScrollView keyboardShouldPersistTaps=‘handled’>
…
</ScrollView>
/>
)
}
In Parent class:
In the parent class where ancestors of modal is there. You need to pass key keyboardShouldPersistTaps=‘handled’`.
class Parent extends Component{
render(){
return(
<ScrollView keyboardShouldPersistTaps=‘handled’> // pass ‘handled’ here also
…
<CountryModal /> // Its the same modal being used as a component in parent class.
</ScrollView>
)
}
Try adding
keyboardShouldPersistTaps={'always'}
to the second ScrollView as well.
Use the 'handled' value for keyboardShouldPersistTaps property because the true value is deprecated. use the keyboardShouldPersistTaps in two ScrollViews and handle your keyboard state in somewhere else by using Keyboard.dismiss() function.

Resources