React Native child component not rendering on onPress event - reactjs

I am trying to render the child component on onPressevent, the console.log works fine but components in the return function doesn't works.
Parent component:
onPress = (img,title,content) => {
this.setState({
show:true,
img:img,
title:title,
content:content
})
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={({item}) => (
<TouchableOpacity
onPress={() => this.onPress(item.urlToImage,item.title,item.content)}
>
<View style={styles.picsCont}>
<Image style={styles.pics} source={{uri: item.urlToImage}}/>
<Text style={{color:'white', fontSize: 15, fontWeight: '700', paddingTop:10}}>
{item.title}
</Text>
</View>
</TouchableOpacity>
)}
keyExtractor={item => item.title}
/>
{this.state.show ?
<NewsView
img={this.state.img}
title={this.state.title}
content={this.state.content}
/> :
null
}
</View>
);
}
}
Child Component:
export default class NewsView extends Component {
render() {
console.log(this.props.img)
return (
<View style={styles.container}>
<Image style={styles.picsCont} source={{uri:this.props.img}} />
<Text style={styles.news}>{this.props.title}</Text>
<Text style={styles.news}>{this.props.content}</Text>
</View>
)
}
}
Thanks for the help...!

It might be the styles. If your child component has position:'absolute', it´s probably under your parent component, you can try to put on your child component view zIndex:10

Related

Navigation from menu item

I'm trying to get a menu item to navigate to another page but for some reason it wont let me do it. I'm a little confused as to how you go about it and any help is welcome!
Import here:
import { NavigationScreenProp } from "react-navigation";
Here is more code:
interface NotificationDropdownProps {
navigation: NavigationScreenProp<any, any>;
}
Here is where function is called:
function renderNotification(notification: INotification) {
return (
<MenuOption
onSelect={() => {
if (notification.type == INotificationType.SYSTEM) {
this.testFunction();
}
}}
>
<View style={[styles.notificationContainer]}>
<View style={styles.iconArea}>
<View style={[styles.iconCircle]}>
<Icon
name={this.getIconType(notification.type)}
color={this.notificationColor(notification.type)}
size={26}
/>
</View>
</View>
<View>
<Text>{notification.text}</Text>
<Text>
{this.getDate(new Date(notification.dateCreated))}
</Text>
</View>
</View>
</MenuOption>
);
}
Test Function:
testFunction(){
this.props.navigation.navigate('NextPage')
};
Error:
undefined is not an object(evaluating'_this2.props.naviagtion.navigate)
Where the function is called:
<View>
<Text>
Notifications
</Text>
{this.props.notifications.length > 0 ? (
<FlatList
contentContainerStyle={{ borderRadius: 10 }}
data={this.props.notifications.slice(0, 5)}
renderItem={({ item }) => this.renderNotification(item)}
keyExtractor={this.keyExtractor}
/>
) : (
<Text>No Notifications!</Text>
)}
</View>;
try with an arrow function to avoid using the context of the function.
testFunction = () => {
this.props.navigation.navigate('NextPage')
};

React Native class component accordion into functional component

The following code displays an accordion but I need to make use of useContext which I understand only works with functional components and I'm having a hard time understand how to convert it into a functional component.
class AnnualFeeScreen extends Component {
state = {
activeSections: [],
};
_renderHeader(section, index, isActive) {
let meanValStatus = '#39D0B5';
if (section.meanDiffVal >= 1.05) {
meanValStatus = '#FCD561';
} else if (section.meanDiffVal < 0.95) {
meanValStatus = '#bbb';
}
return (
<View style={styles.flexRow}>
<View style={{flex:2}}>
<Text style={styles.h6}>{!isActive ? '+' : '-'} {section.title}</Text>
</View>
<View style={styles.flex}>
<Text style={[styles.h6, {textAlign: 'right'}]}>{Math.round((section.titleValue) / 12, 0)} kr/mån</Text>
</View>
<View style={[styles.circleStatus, {backgroundColor: meanValStatus}]}></View>
</View>
);
};
_renderContent = section => {
return (
<View>
{section.content.map((item, key) =>
<View style={styles.accordionContent} key={key}>
<View style={styles.flexRow}>
<View style={{flex: 2}}>
<Text style={[styles.p, {fontWeight: 'normal'}]}>{item.title}</Text>
</View>
<View style={styles.flex}>
<Text style={[styles.p, {fontWeight: 'normal', textAlign: 'right'}]}>{Math.round((item.value * aptPercentage) / 12, 0)} kr/mån</Text>
</View>
</View>
</View>
)}
</View>
);
};
_updateSections = activeSections => {
this.setState({ activeSections });
};
render () {
return (
<ScrollView style={styles.backgroundPrimary} showsVerticalScrollIndicator='false'>
<View style={styles.backgroundSecondary}>
<View style={styles.container}>
<Accordion
sections={brfCostRows}
activeSections={this.state.activeSections}
renderHeader={this._renderHeader}
renderContent={this._renderContent}
onChange={this._updateSections}
sectionContainerStyle={styles.accordion}
underlayColor='transparent'
/>
</View>
</View>
</ScrollView>
);
};
};
To fetch data with axios I use the following in other screens but it's not working with the class component:
const { state, fetchUser } = useContext(UserContext);
And in the view:
<NavigationEvents onWillFocus={fetchUser} />
I've tried to remove the render part change the first part to the following but it's complaining about the first function _renderHeader (Unexpected token):
const AnnualFeeScreen = () => {
First of all while converting, class component to functional component with hooks, you must note that, there won't be a this variable inside functional component. Secondly the state inside a functional component would need to be implemented using useState hook
const AnnualFeeScreen () => {
const [activeSections, setActiveSections] = useState([]);
const _renderHeader(section, index, isActive) {
let meanValStatus = '#39D0B5';
if (section.meanDiffVal >= 1.05) {
meanValStatus = '#FCD561';
} else if (section.meanDiffVal < 0.95) {
meanValStatus = '#bbb';
}
return (
<View style={styles.flexRow}>
<View style={{flex:2}}>
<Text style={styles.h6}>{!isActive ? '+' : '-'} {section.title}</Text>
</View>
<View style={styles.flex}>
<Text style={[styles.h6, {textAlign: 'right'}]}>{Math.round((section.titleValue) / 12, 0)} kr/mån</Text>
</View>
<View style={[styles.circleStatus, {backgroundColor: meanValStatus}]}></View>
</View>
);
};
const _renderContent = section => {
return (
<View>
{section.content.map((item, key) =>
<View style={styles.accordionContent} key={key}>
<View style={styles.flexRow}>
<View style={{flex: 2}}>
<Text style={[styles.p, {fontWeight: 'normal'}]}>{item.title}</Text>
</View>
<View style={styles.flex}>
<Text style={[styles.p, {fontWeight: 'normal', textAlign: 'right'}]}>{Math.round((item.value * aptPercentage) / 12, 0)} kr/mån</Text>
</View>
</View>
</View>
)}
</View>
);
};
const _updateSections = activeSections => {
setActiveSections(activeSections);
};
return (
<ScrollView style={styles.backgroundPrimary} showsVerticalScrollIndicator='false'>
<View style={styles.backgroundSecondary}>
<View style={styles.container}>
<Accordion
sections={brfCostRows}
activeSections={activeSections}
renderHeader={_renderHeader}
renderContent={_renderContent}
onChange={_updateSections}
sectionContainerStyle={styles.accordion}
underlayColor='transparent'
/>
</View>
</View>
</ScrollView>
);
};

How to pass Parent Flatlist's Index value to Child Flatlist's onPress function?

How to pass parent Flatlist's index value to child Flatlist's function so I can use it in function and change value by setState.
So how to pass parent Flatlist's index value to child Flatlist's function so I can use it in function and change value by setState.
It starts with a list that built-in state
constructor(props) {
super(props);
this.state = {
list: [
{
question: 'il veicolo ha la gomma forata?',
answers: [
{
radioButtonValue: false,
text: strings.CONFIRMVIEW_yes,
},
{
radioButtonValue: true,
text: strings.CONFIRMVIEW_no,
},
],
},
]
}
}
checkBoxSelection = (item, index) => {
// if (item.radioButtonValue == index) {
// this.list.answers[index].radioButtonValue = true
// }
console.log(this.state.list[0].answers[index].radioButtonValue)
}
_renderItem = ({ item, index }) => {
return (
<View style={styles.cellView}>
<Text style={styles.questionText}>
{item.question.toUpperCase()}
</Text>
<FlatList
data={item.answers}
horizontal={true}
showsHorizontalScrollIndicator={true}
scrollEnabled={true}
bounces={false}
renderItem={this._renderItemOptions}
/>
{/* <View style={styles.yesNoRadioButtonView}>
<View style={styles.yesChekboxView}>
<TouchableOpacity onPress={ () => {console.log("TEST1"); this.checkBoxSelection()} }>
<Image source={(item.answers == index) ? AppImages.radioOn : AppImages.radioOff} style={styles.radioButton} />
</TouchableOpacity>
<Text style={styles.yesNoText}>
{strings.CONFIRMVIEW_yes}
</Text>
</View>
<View style={styles.noRadioButtonView}>
<TouchableOpacity onPress={() => { this.checkBoxSelection.bind(this) }}>
<Image source={(item.answers == 0) ? AppImages.radioOn : AppImages.radioOff} style={styles.radioButton} />
</TouchableOpacity>
<Text style={styles.yesNoText}>
{strings.CONFIRMVIEW_no}
</Text>
</View>
</View> */}
</View>
)
}
_renderItemOptions = ({ item, index }) => {
return (
<View>
<View style={styles.yesNoRadioButtonView}>
<TouchableOpacity onPress={() => { this.checkBoxSelection(item, index) }}>
<View style={styles.yesChekboxView}>
<Image
source={item.radioButtonValue ? AppImages.radioOn : AppImages.radioOff}
style={styles.radioButton}
/>
<Text style={styles.yesNoText}>
{item.text}
</Text>
</View>
</TouchableOpacity>
</View>
</View>
)
}
render() {
return (
<Container>
<Content style={styles.container}>
<FlatList
data={this.state.list}
showsVerticalScrollIndicator={false}
scrollEnabled={false}
bounces={false}
renderItem={this._renderItem}
/>
</Content>
<SafeAreaView>
<TouchableOpacity
style={[LayoutStyle.appBtn1]}
>
<Text style={[LayoutStyle.appBtnText1]}>
{strings.DAMAGE_SURVEY_comeOn.toUpperCase()}
</Text>
</TouchableOpacity>
</SafeAreaView>
</Container>
)
}
In Parent Flatlist's renderItem function
replace
renderItem = { () => {this.renderItemOptions(item, index)}}
with
renderItem={(childData) => this._renderItemOptions(childData, index)}
and then in child Flatlist's renderItemOption function need to get parentIndex with another name.
_renderItemOptions = ({ item, index }, parentIndex) => {
console.log("hello")
return (
<View>
<View style={styles.yesNoRadioButtonView}>
<TouchableOpacity onPress={() => { this.checkBoxSelection(item, index, parentIndex) }}>
<View style={styles.yesChekboxView}>
<Image
source={item.radioButtonValue ? AppImages.radioOn : AppImages.radioOff}
style={styles.radioButton}
/>
<Text style={styles.yesNoText}>
{item.text}
</Text>
</View>
</TouchableOpacity>
</View>
</View>
)
}
Try updating your renderItem prop in your FlatList to explicitly pass the index
renderItem={({item, index}) => this._renderItemOptions(item, index)}

Close modal on click button react native

I have a modal that shown on a button click and the modal is fetched from another component using prop.
In the modal there is a button to close the modal, How to close the modal onclick the button. I have tried but doesn't worked.
//InvalidUser
const InvalidUser = (props) => (
<Modal
visible={props.display}
animationType="slide"
onRequestClose={() => console.log('closed')}
>
<View style={styles.modalBox}>
<View style={{width: 300}}>
<Text style={styles.text}>
{props.data}
</Text>
<TouchableOpacity
onPress={() =>
this.closeModal()
}>
<Text style={styles.buttonOk}>Ok</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
);
//Login
export default class LoginFirst extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
modalVisible: false
};
}
nextBtn = () => {
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (this.state.email !== '') {
if (reg.test(this.state.email) === false) {
}
else {
this.setState({modalVisible: true});
}
}
}
render() {
let notRegistered = this.state.email+' is not recognized as a registered user. Please contact us for further assistance.';
return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.scroller}>
<View
style={styles.inputSection}
>
<Text style={styles.label}>Email Address:</Text>
<View style={styles.section}>
<Image
style={styles.icon}
source={require('../../../../assets/user.png')}
/>
<TextInput
style={styles.input}
placeholder='johnsmith#gmail.com'
underlineColorAndroid='transparent'
onChangeText={(text) => this.setState({email:text})}
/>
</View>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.nextBtn()
}
>
<Text style={styles.next}>Next</Text>
</TouchableOpacity>
</View>
</ScrollView>
<InvalidUserModal
data={notRegistered}
display={this.state.modalVisible}
/>
</View>
);
}
}
The above code is perfectly displaying the modal, but I cannot close the modal. Is there any way to close.
Please have a look into below image.
from parent component, create closeModal function and pass it to InvalidUserModal
closeModal = () => {
this.setState({modalVisible: false});
}
<InvalidUserModal
data={notRegistered}
display={this.state.modalVisible}
closeModal={this.closeModal}
/>
and call it inside InvalidUserModal on press the button
<TouchableOpacity onPress={props.closeModal}>
<Text style={styles.buttonOk}>Ok</Text>
</TouchableOpacity>
For parent, pass the closeModal method as a props to your component
class LoginFirst extends Component {
closeModal = () => {
this.setState({modalVisible: false});
}
render() {
return (
<InvalidUserModal
data={notRegistered}
display={this.state.modalVisible}
closeModal={this.closeModal}
/>
)
}
}
For your modal component
<Modal
visible={props.display}
animationType="slide"
onRequestClose={() => console.log('closed')}
>
<TouchableOpacity onPress={props.closeModal}>
<Text style={styles.buttonOk}>Ok</Text>
</TouchableOpacity>
</Modal>

How to do the multi Button onPress functions in one common component - React native

I have a component call ButtonLayout.js
export const ButtonLayout = () => {
return (
<View style={styles.row}>
<TouchableOpacity >
<Text>Book Now</Text>
</TouchableOpacity>
<TouchableOpacity >
<Text>Schedule</Text>
</TouchableOpacity>
</View>
)
}
and i have import this component to another common component called mapComponent and it look like following.
return (
<View style={styles.container}>
<MapView
provider={MapView.PROVIDER_GOOGLE}
style={styles.map}
region={this.props.region}
>
<MapView.Marker
coordinate={this.props.region}
pinColor='green'
/>
</MapView>
<ButtonLayout style={{ marginBottom: 5 }} />
</View>
);
so my question is how can i handle the onPress() function of the buttons in ButtonLayout.js from index.js ?
Make your ButtonLayout component accept callback props, like so:
export const ButtonLayout = ({onBook, onSchedule}) => (
<View style={styles.row}>
<TouchableOpacity onPress={onBook}>
<Text>Book Now</Text>
</TouchableOpacity>
<TouchableOpacity onPress={onSchedule}>
<Text>Schedule</Text>
</TouchableOpacity>
</View>);
Then, pass the callbacs in the parent component’s render function as props
<ButtonLayout onBook={…} onSchedule={…} />
Don’t forget to bind the context to the callbacks
In your button Buttonlayout.js define like this:
<TouchableOpacity onPress={() => this.props.onPress()}>
<Text>Book Now</Text>
</TouchableOpacity>
And define onPress function on each file you use this component just like.
<ButtonLayout style={{ marginBottom: 5 }} onPress={() => {'your logic..'}}/>
Define your callback variables in ButtonLayout and add them to your touchables.
export const ButtonLayout = ({ onBookPress, onSchedulePress }) => {
return (
<View style={styles.row}>
<TouchableOpacity onPress={onBookPress}>
<Text>Book Now</Text>
</TouchableOpacity>
<TouchableOpacity onPress={onSchedulePress} >
<Text>Schedule</Text>
</TouchableOpacity>
</View>
)
}
Define your callbacks in index:
indexOnBookPress = () => {
...do something
}
indexOnSchedulePress = () => {
...do something
}
return (
<View style={styles.container}>
<MapView
provider={MapView.PROVIDER_GOOGLE}
style={styles.map}
region={this.props.region}
>
<MapView.Marker
coordinate={this.props.region}
pinColor='green'
/>
</MapView>
<ButtonLayout style={{ marginBottom: 5 }} onBookPress={this.indexOnBookPress} onSchedulePress={this.indexOnSchedulePress} />
</View>
);

Resources