How to set child view programmatically, not with markup in React Native? - react-native

I've spent couple of hours but didn't find solution.
I expect something like:
this.view1.props.children = view2
but not like:
<View1><View2/></View1>
I'm trying to make something like navigation controller:
import React, { Component } from 'react';
import { View, Button } from 'react-native';
let v1 = <View />;
let v2 = <View />;
export default class App extends Component {
constructor(){
super();
this._openView1 = this._openView1.bind(this);
this._openView2 = this._openView2.bind(this);
}
openSection(view){
// How to implement this method?
this.sectionContentWrapper.props.children = view;
}
_openView1(){
this.openSection(v1)
}
_openView2(){
this.openSection(v2)
}
render() {
return (
<View>
<Button
title="Go to v1"
onPress={this._openView1}/>
<Button
title="Go to v2"
onPress={this._openView2}/>
<View ref={(ref) => this.sectionContentWrapper = ref} />
</View>
);
}
}
Does anyone know how to do it, please?

You could store it in state
import React, { Component } from 'react';
import { View, Button } from 'react-native';
let v1 = <View />;
let v2 = <View />;
export default class App extends Component {
state = { childView: null }
openSection = view => {
this.setState({ childView: view }
}
_openView1 = () => this.openSection(v1)
_openView2 = () => this.openSection(v2)
render() {
return (
<View>
<Button
title="Go to v1"
onPress={this._openView1}/>
<Button
title="Go to v2"
onPress={this._openView2}/>
<View>{this.state.childView}</View>
</View>
);
}
}

Related

How to Call child function from parent component in React Native functional component?

Hello I want to call showModal() in AddModalBox.js from App.js by using useRef() to access AddModalBox.js into App.js but is doesn't work it said:
showmodal.showMdal() is not a function...
Thanks for help...
App.Js
import React ,{useRef,useState} from 'react'
import {View,Text,StyleSheet,Image,Button,FlatList, Alert } from 'react-native'
import data from './components/Data'
import Swipeout from 'react-native-swipeout'
import AddModalBox from './components/AddModalBox'
const App=()=>{
const showmodal =useRef()
const callModal=()=>{
showmodal.showModal()
}
return(
<>
<View style={{backgroundColor:'red',height:10,flex:1,flexDirection:'row',marginTop:10}}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'flex-end'}}>
<Button title="+" onPress={callModal}/>
</View>
</View>
<FlatList data={data} renderItem={({item,index})=> <Mydata item={item} index={index} parentFlatList={refreshFlatList}/>}
keyExtractor={item=>item.id}
/>
<AddModalBox ref={showmodal}/>
</>
)
}
export default App;
AddModalBox.js
I want to call showModal() function from App.js …
import React,{useRef}from 'react'
import {Text,View,Button,Dimensions} from 'react-native'
import Modal from 'react-native-modalbox'
import { useState } from 'react'
//import data from './components/Data'
var screen=Dimensions.get('window')
const AddModalBox=(props)=>{
let isOpen=false
// I want call this function in App.js
const showModal=()=>{
isOpen=true
}
return(
<>
<Modal style={{width:screen.width-80,height:200,justifyContent:'center'}}
position='center'
backdrop={true}
onClosed={()=>isOpen=false}
ref={show}
isOpen={isOpen}
>
<Text>hello from modal</Text>
</Modal>
</>
)
}
export default AddModalBox;
Let me show you an example to use parameters between child and parent components.
This example is about variable visibility, but you can see and get insight to use on your code:
//Parent component
class Parent extends Component {
state = {
viewClhild: false
}
goToChild = (task) => {
this.setState({viewChild: true})
}
onShowClhildChange(viewChild) {
this.setState({ viewChild });
}
render() {
<View>
{
this.state.viewChild
? <ChildScreen onShowClhildChange={this.onShowClhildChange.bind(this)} />
: <Text>Show Parent</Text>
}
<Button
onPress={() => {this.goToChild()}}
>
<Text style={button.text}>Entrar</Text>
</Button>
</View>
}
}
//Child Component
class ChildScreen extends Component {
isChildVisible = (isVisible) => {
this.setState({ viewChild: isVisible })
if (this.props.onShowClhildChange) {
this.props.onShowClhildChange(isVisible);
}
}
constructor (props) {
super(props);
this.state = {
viewChild: this.props.viewChild
}
}
render() {
return (
<View>
<Button
onPress={() => this.isChildVisible(false)}
>
<Text>CLOSE CHILD SCREEN</Text>
</Button>
</View>
)
}
}

add onPress to first component and call it on second component

I'm a beginner in react-native I want to make add ( + ) button on the header of the first component when user click on onPress it will create a new form and the form is the second component
In App.js SetUp Navigation like below:
import { createAppContainer, createStackNavigator } from "react-navigation";
import MainScreen from "./screens/MainScreen";
import SecondScreen from "./screens/SecondScreen";
const AppNavigator = createStackNavigator({
MainScreen: {
screen: MainScreen
},
SecondScreen: {
screen: SecondScreen,
},
})
const App = createAppContainer(AppNavigator);
export default App;
In Main Screen
import React, { Component } from "react";
import {
View,
Button,
} from "react-native";
class MainScreen extends Component {
handleOnPress = () => {
this.props.navigation.navigate("SecondScreen");
};
render() {
return (
<View>
<Button
onPress={this.handleOnPress}
title="Button"
color="#841584"
/>
</View>
);
}
}
export default MainScreen;
It will redirect you to second screen
You can set ref of Form component
<FormsComponent
ref={ref => {
this.formComponent = ref;
}}
/>
You should pass function as prop for Header component
<HeaderComponent addNewForm={this.addNewForm} />
Parent component will call function of form component when click in header component using ref
addNewForm = () => {
this.formComponent.addNewForm();
};
App Preview
Complete Code
import React, { Component } from "react";
import { View, Text, FlatList } from "react-native";
class HeaderComponent extends Component {
render() {
return (
<View style={{ height: 80, backgroundColor: "red", paddingTop: 24 }}>
<Text style={{ padding: 20 }} onPress={this.props.addNewForm}>
Call Function of Form Component
</Text>
</View>
);
}
}
class FormsComponent extends Component {
addNewForm = () => {
alert("add new form");
};
render() {
return (
<FlatList
data={[{ key: "Form1" }, { key: "Form2" }]}
renderItem={({ item }) => <Text>{item.key}</Text>}
style={{ flex: 1 }}
/>
);
}
}
export default class App extends Component {
addNewForm = () => {
this.formComponent.addNewForm();
};
render() {
return (
<View style={{ flex: 1 }}>
<HeaderComponent addNewForm={this.addNewForm} />
<FormsComponent
ref={ref => {
this.formComponent = ref;
}}
/>
</View>
);
}
}

In React-native, how to handle checkbox in Listview?

In my react-native app, I am trying to show my contact details with checkboxes for selecting.
Here is my code:
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData, sectionID, rowID) => (
<TouchableHighlight onPress={() => this.goRideDetails(rowData)}>
<Text style={styles.rideHeader}>{rowData.name} </Text>
<CheckBox
checked={this.state.checked}
onCheckBoxPressed={() =>
this.setState({ checked: !this.state.checked })
}
/>
</TouchableHighlight>
)}
/>
In my view checkbox is displaying on every row, but not working.
Any one can help me. Thanks in advance.
You can easily do this with component separation. Please, take a look here:
export default class ContactList extends Component {
static propTypes = {
contacts: React.PropTypes.array,
}
static defaultProps = {
contacts: [],
}
constructor(){
super();
this._renderRow = this._renderRow.bind(this);
}
_renderRow(rowData,sectionID,rowID) {
return <Contact info={ rowData } />;
}
render() {
return (
<ListView
dataSource={ this.props.contacts }
renderRow={ this._renderRow }
/>
);
}
}
export class ContactList extends Component {
static propTypes = {
info: React.PropTypes.object.isRequired,
}
constructor(){
super();
this.goRideDetails = this.goRideDetails.bind(this);
this.setChecked = this.setChecked.bind(this);
}
goRideDetails() {
//your logic here
}
setChecked() {
this.props.info.checked = !this.props.info.checked; //will be much better to do it with redux and action creators
}
render() {
return (
<TouchableHighlight onPress={ this.goRideDetails }>
<Text style={ styles.rideHeader }>{this.props.info.name} </Text>
<CheckBox checked={ this.props.info.checked } onCheckBoxPressed={ this.setChecked } />
</TouchableHighlight>
);
}
}
After that you can simply call:
<ContactList contacts={this.state.dataSource} />
in your jsx and voila.
Important note: Do not use array functions inside your jsx code blocks.
Important note 2: Try to start using redux or flux for storing state of your application. It will be provide much better code design.
Hope, it will help.
import React , {Component} from 'react'
import {
Text,
View,
ListView,
StyleSheet,
TouchableOpacity,
Image,
} from 'react-native'
import CheckBox from 'react-native-checkbox'
var Folder = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
var folder = '' ////// all the new folder
var check_folder = [] ////// all the check box conditions
class ApproveContent extends Component {
///////// all the upper thing that are global variable for this script is has same value as that of the state the only reason we are using this because of the layout update //////////
state={
folder:[],
data:[],
check:[]/////// this need to do just to upadte the layout of the check box
}
render(){
return(
<View style = {{flex:1,backgroundColor:'white',alignItems:'center'}}>
<ListView
dataSource={Folder.cloneWithRows(this.state.folder)}
renderRow={(rowData,rowID,sectionID) => <View style = {{ alignItems: 'center',margin:5}}>
<TouchableOpacity style = {{width:Dimension.ScreenWidth/1.2,height:Dimension.ScreenHeight/6,flexDirection: 'row',alignItems:'center'}}
onPress={() => {}}>
<CheckBox
label=''
labelBefore={false}
checked={this.state.check[sectionID]}
checkboxStyle = {{marginLeft: 20}}
onChange={(checked) => {
this.setState({
check:!this.state.check
})
if(check_folder[sectionID] == false){
check_folder[sectionID] = true
this.setState({
check:check_folder// has to do this because we cant change the single element in the array
})
}else{
check_folder[sectionID] = false
this.setState({
check:check_folder// has to do this because we cant change the single element in the array
})
}
console.log(check_folder)a
}}
/>
</TouchableOpacity>
</View>
}
/>
</View>
)}
}
export default ApproveContent
const style = StyleSheet.create({
TextStyle:{
fontFamily: 'Roboto-Bold',
fontSize:15,
},
approveButton: {
bottom:0,
left:0,
alignItems: 'center',
}
})

react-native router flux Actions is not navigating to other page

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
Button
} from 'react-native';
import Actions from 'react-native-router-flux';
import First from './First';
export default class Home extends Component{
componentWillMount() {
}
render(){
return(
<View>
<View style={{height:220,backgroundColor:'#DCDCDC'}}>
<Image style={{width:120,height:120,top:50,left:120,backgroundColor:'red'}}
source={require('./download.png')} />
</View>
<View style={{top:30}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views}
onPress = {()=>{ Actions.First({customData: 'Hello!'}) }}>
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Profile </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views1} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Health Tracker </Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
In the above code, Actions in not working means not navigating to First.js page, how can i edit my code, and i have not written anything in ComponentWillMount() function, what i should write inside that?ataomega
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity
} from 'react-native';
import Home from './Home';
export default class Prof extends Component{
constructor(){
super()
}
render(){
return (
<Navigator
initialRoute = {{ name: 'Home', title: 'Home' }}
renderScene = { this.renderScene }
navigationBar = {
<Navigator.NavigationBar
style = { styles.navigationBar }
routeMapper = { NavigationBarRouteMapper } />
}
/>
);
}
renderScene(route, navigator) {
if(route.name == 'Home') {
return (
<Home
navigator = {navigator}
{...route.passProps}
/>
)
}
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<View>
<TouchableOpacity
onPress = {() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftButton }>
Back
</Text>
</TouchableOpacity>
</View>
)
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (route.openMenu) return (
<TouchableOpacity
onPress = { () => route.openMenu() }>
<Text style = { styles.rightButton }>
{ route.rightText || 'Menu' }
</Text>
</TouchableOpacity>
)
},
Title(route, navigator, index, navState) {
return (
<Text style = { styles.title }>
{route.title}
</Text>
)
}
};
First of all I recommend you to create a rounter component and make your app launch from there:
Something like this
import { Scene, Router, ActionConst } from 'react-native-router-flux';
import First from 'yourRoute';
const RouterComponent = () => {
<Router>
<Scene
key="First"
component={First}
initial />
... your other scenes
</Router>
}
export default RouterComponent;
then in your index page or wherever you load from just add this component
import React, { Component } from 'react'
import RouterComponent from './Router'
class AppContainer extends Component {
render() {
return (
<RouterComponent />
);
}
}
export default AppContainer;
now you can call it from your code. Any doubts ask them :P

Sharing strings to other native applications not working in react native

I have been following this tutorial, however, when I go to run the application after dropping the code in, it doesn't seem to work. The tutorial seems fairly simple, so I can not understand why it is not working.
The error message I'm getting is:
import React from 'react'
import { View, Text, StyleSheet, Image, Share } from 'react-native'
class ShareLesson extends Component {
constructor(props) {
super(props);
this._shareMessage = this._shareMessage.bind(this);
this._showResult = this._showResult.bind(this);
this.state = { result: ''};
}
_showResult(result) {
this.setState({result});
}
_shareMessage() {
Share.share({
message: 'This is a simple shared message'
}).then(this._showResult);
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._shareMessage}>
<Text style={styles.welcome}>
Share
</Text>
</TouchableHighlight>
<Text>
{JSON.stringify(this.state.result)}
</Text>
<View>);
}
}
Tabs Component
class Tabs extends Component {
_changeTab (i) {
const { changeTab } = this.props
changeTab(i)
}
_renderTabContent (key) {
switch (key) {
case 'today':
return <Home />
case 'share':
return <Share />
case 'savequote':
return <SaveQuote />
case 'moremenu':
return <MoreMenu />
}
}
render () {
const tabs = this.props.tabs.tabs.map((tab, i) => {
return (
<TabBarIOS.Item key={tab.key}
icon={tab.icon}
selectedIcon={tab.selectedIcon}
title={tab.title}
onPress={() => this._changeTab(i)}
selected={this.props.tabs.index === i}>
{this._renderTabContent(tab.key)}
</TabBarIOS.Item>
)
})
return (
<TabBarIOS tintColor='black'>
{tabs}
</TabBarIOS>
)
}
}
export default Tabs