How do I let a screen know other screen's state - javascript

Now I am trying to let a screen containing some lists know other screen's state.
The main screen contains some Form Components which user can input text to.
Other screens, Form Components contain some TextInput forms.
If a user inputs some texts into some form and then if this user puts a back button or a save-button, I want to change the main screen's state of these form components to be like "Editing", "Not Edit" or "Complete".
How to change the state of each form component's state on the Main screen?
This picture is the main screen. Please focus on Red characters. There will be changed if a user will input some text into a form on other screens.
This is a input-screen
handleOnpress() {
const db = firebase.firestore();
const { currentUser } = firebase.auth();
db.collection(`users/${currentUser.uid}/form1`).add({
form1 : [
{ fullname: this.state.fullname },
{ middleName: this.state.middleName },
{ reason: this.state.reason },
{ birthPlaceCity: this.state.birthPlaceCity },
{ birthPlaceCountry: this.state.birthPlaceCountry },
{ Citizinchip: this.state.Citizinchip },
{ aboutMaridge: this.state.aboutMaridge },
{ fromTermOfMaridge: this.state.fromTermOfMaridge },
{ ToTermOfMaridge: this.state.ToTermOfMaridge },
{ nameOfSpouse: this.state.nameOfSpouse },
{ birthdateOfSpouse: this.state.birthdateOfSpouse },
{ fromTermOfExMaridge: this.state.fromTermOfExMaridge },
{ ToTermOfExMaridge: this.state.ToTermOfExMaridge },
{ nameOfExSpouse: this.state.nameOfExSpouse },
{ birthdateOfExSpouse: this.state.birthdateOfExSpouse }]
})
.then(() => {
this.props.navigation.goBack();
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<ScrollView style={styles.container}>
<InfoHeader navigation={this.props.navigation}>申請者情報1
</InfoHeader>
<Notes />
<QuestionTextSet onChangeText={(text) => { this.setState({
fullname: text }); }} placeholder={'例:留学太郎'}>姓名(漢字表記)
</QuestionTextSet>
<QuestionTextSet onChangeText={(text) => { this.setState({
middleName: text }); }}>本名以外に旧姓・通称名(通名)・別名など他の名前が
あればローマ字で記入</QuestionTextSet>
<QuestionTextSet onChangeText={(text) => { this.setState({
reason: text }); }} placeholder={'例:結婚・離婚/ご両親の離婚のためな
ど'}>別名がある方はその理由</QuestionTextSet>
<SubmitButton style={styles.saveButton} onPress=
{this.handleOnpress.bind(this)}>保存</SubmitButton>
<Copyrights />
</ScrollView>
);
This is the main screen.
class WHApply extends React.Component {
render() {
return (
<ScrollView style={styles.container}>
<WHApplyBar navigation={this.props.navigation} />
<WHApplyIndexBar />
<HWApplyMailBar />
<HWApplyList navigation={this.props.navigation} />
<Agreement />
<SubmitButton>同意して送信</SubmitButton>
<Logout />
<Copyrights />
</ScrollView>
);
}
}
And this is a code of HWApplyList.
This component is import to the main screen.
class HWApplyList extends React.Component {
state = {
fontLoaded: false,
}
async componentWillMount() {
await Font.loadAsync({
FontAwesome: fontAwesome,
});
this.setState({ fontLoaded: true });
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {
this.props.navigation.navigate('PersonalInfo1'); }} >
<View style={styles.listBox}>
<Text style={styles.listBoxText}>
申請者情報1
</Text>
<View style={styles.inputBotton}>
<Text style={styles.inputBottonText}>未入力</Text>
</View>
<View style={{ flex: 1, justifyContent: 'center' }}>
{
this.state.fontLoaded ? (
<View style={styles.navigationButton}>
<Text style={styles.navigationButtonIcon}>{'\uf0da'}
</Text>
</View>
) : null
}
</View>
</View>
</TouchableOpacity>

In addition to the previous answer, you will also need to pass a handler function to the screen child. This handle function will allow your child screen to modify the parent's state.
Something like
onChange(value) {
this.setState({value});
}
render() {
return (
<Screen1 value={this.state.value} onChange={this.onChange}/>
<Screen2 value={this.state.value}/>
)
}

When you start to make many components that uses each other's state, Using a tool like "redux" makes it much easier.
Instead of putting your data ( that's you want it to be shared with the other components ) in a particular component state. you can create a common state for the whole app and you can access this state from any component.
here's a good article:
Understanding Redux: The World’s Easiest Guide to Beginning Redux

Related

React native flat list not rendering items

I hope you're doing okay
I'm experiencing something weird with my react-native project, The FlatList items in some of the pages aren't displayed, even though I can see them when I console.log(json.items).
Earlier today, everything worked fine. all the pages displayed their lists as they should on my device. then I started working on a new search page on snack & I added status bar, I tested and it worked on snack before adding the new code and creating the new files in my app.
The issue I'm having now is, the list on the first page is displayed, subsequent pages after that do not show list items. including the new search page that works on snack
I'll go ahead and post my code now, the first set is for the page whose listitems are displayed correctly:
App.js
class ProfileActivity extends Component
{
// Setting up profile activity title.
static navigationOptions = ({ navigation }) =>
{
return {
title: 'Home',
headerStyle : {
backgroundColor: '#00b47a',
elevation: 0
},
headerTitleStyle: {
color: 'white'
},
cardStyle: { backgroundColor: '#fff' },
headerLeft: null,
headerRight: (
<View style={{ alignSelf: 'center', alignItems: 'center', display: 'flex', flexDirection: 'row', justifyContent: 'space-evenly'}}>
<Icon containerStyle={{ paddingRight: 10 }}
color='#fff' onPress={()=> navigation.getParam('openBottomSheet')()}
name="menu" />
<Icon containerStyle={{ paddingRight: 15 }}
color='#fff' onPress={()=> navigation.getParam('openSearchPage')()}
name="search" /></View>
)
}
};
constructor () {
super()
this.state = { toggled: false }
}
componentDidMount() {
this.props.navigation.setParams({ openBottomSheet: this.onOpenBottomSheet });
this.props.navigation.setParams({ openSearchPage: this.onOpenSearchPage });
}
onOpenBottomSheet = () => {
this.Standard.open();
}
onOpenSearchPage = () => {
this.props.navigation.navigate('sixth');
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<StatusBar
animated={true}
backgroundColor="#00b47a"
barStyle={'light-content'}
showHideTransition={'slide'}
hidden={false} />
<MarketList navigation={this.props.navigation} />
<RBSheet
ref={ref => {
this.Standard = ref;
}}
>
...
</RBSheet>
</View>
);
}
}
Market.js
export default class MarketList extends React.Component {
constructor(props) {
super(props)
this.state = {
items: '',
};
this.animateList = new Animated.Value(0);
}
componentDidMount() {
Animated.timing(this.animateList, {
toValue: 1,
duration: 500,
}).start();
}
render() {
const rowStyles = [
styles.itemList,
{ opacity: this.animateList },
{
transform: [
{ scale: this.animateList },
],
},
];
fetch('https://mvmarket.xyz/nativeuserapp/home.php')
.then((response) => response.json())
.then((json) => {
this.setState({
items: json.items,
})
})
.catch((error) => {
console.error(error);
});
return (
<View style={styles.container}>
<FlatList
data={this.state.items}
renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("fourth",{market:item.name})}><Animated.View style={rowStyles}><View style={styles.item}><Text style={styles.market}>{item.name}</Text><Text style={styles.location}>{item.Location}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></Animated.View></TouchableOpacity>}
/>
</View>
);
}
}
This next set is for one of the pages that don't show list items
App.js
class ProductsActivity extends Component {
static navigationOptions =
{
title: 'Products',
headerStyle : {
backgroundColor: '#00b47a',
elevation: 0
},
cardStyle: { backgroundColor: '#fff' },
headerTitleStyle: {
color: 'white'
},
};
render() {
return(
<View>
<StatusBar
animated={true}
backgroundColor="#00b47a"
barStyle={'light-content'}
showHideTransition={'slide'}
hidden={false} />
<ProductsList navigation={this.props.navigation} />
</View>
);
}
}
Products.js
export default class ProductsList extends React.Component {
constructor(props) {
super(props)
this.state = {
items: '',
};
}
render() {
fetch('https://mvmarket.xyz/nativeuserapp/products.php')
.then((response) => response.json())
.then((json) => {
this.setState({
items: json.items,
})
}).catch((error) => {
console.error(error);
console.log(error);
});
return (
<View style={styles.container}>
<FlatList
data={this.state.items}
renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("fifth",{market: this.props.navigation.state.params.market, type:item.type})} style={styles.itemList}><View style={styles.item}><Text style={styles.market}>{item.type}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></TouchableOpacity>}
/>
</View>
);
}
}
I'm leaving the URL there so you can confirm yourself that the data is actually fetched. Its driving me crazy, been on it for like 4 hrs.
Thank you
I think you don't really understand lifecycle methods of a React Component. It's important to understand those concepts before jumping into code. You can check here
When you put your fetch call in render, and on then you do a setState() you are making this infinitely. This happens because you are always providing new values to items.
The ideal is to have a model layer to handle those type of calls, but this is an architecture thing, to be less complex, you can use Container/Presentation pattern.
In the Container/Presentation pattern, you have a ContainerComponent which is responsible to do requests, handle callbacks, and provide data to the Presentation component, which would be responsible to just render things.
If you don't want to use this pattern, at least put this fetch call in componentDidMount method.
Thank you all for your suggestions, duly noted and appreciated.
#Witalo-Benicio #Andris-laduzans #Drew-reese
I've fixed it, by changing
class SearchMarketActivity extends Component {
static navigationOptions = {
headerShown: false,
cardStyle: {
backgroundColor: 'white'
}
}
render() {
return(
<View>
<StatusBar
animated={true}
backgroundColor="#585858"
barStyle={'light-content'}
showHideTransition={'slide'}
hidden={false} />
<SearchMarket navigation={this.props.navigation} />
</View>
)
}
}
to
class SearchMarketActivity extends Component {
static navigationOptions = {
headerShown: false,
cardStyle: {
backgroundColor: 'white'
}
}
render() {
return(
<SearchMarket navigation={this.props.navigation} />
)
}
}
After, I added the StatusBar to the <SearchMarket /> component being imported

Both the parent and the child components get rendered simultaneously in react-native

I have a parent component that maps through an array of chapters and renders (an exercise) a child component for every item found and passes an array of exercises to it.
class ExercisesScreen extends Component {
showSelectedItemList = (screenName, text) => {
Navigation.push("ExercisesStack", {
component: {
name: screenName,
options: navOptionsCreator(text)
}
});
};
get chapters() {
return this.props.chapters.map(chapter => (
<TouchableOpacity key={chapter.id}>
<ExercisesList
onPress={() =>
this.showSelectedItemList(chapter.screenName, chapter.name)
}
exercises={chapter.exercises}
/>
</TouchableOpacity>
));
}
render() {
return <View>{this.chapters}</View>;
}
}
const mapStateToProps = state => ({
chapters: chaptersSelector(state)
});
When this child component receives the array of exercises, it maps through it and renders a list of exercises.
class ExercisesList extends Component {
render() {
return this.props.exercises.map(exercise => (
<View key={exercise.id}>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.props.showSelectedItemList(exercise.screenName, exercise.name)
}
>
<Image source={exercise.icon}/>
<View>
<Text>{exercise.name}</Text>
</View>
<Image source={arrow} />
</TouchableOpacity>
<View />
</View>
));
}
}
ExercisesList.propTypes = {
onPress: PropTypes.func,
exercises: PropTypes.arrayOf(PropTypes.object)
};
The result I get from both components rendered simultaneously:
The question is, what should I do in order for them to render themselves separately and show the corresponding ExercisesList for every chapter in ExercisesScreen?
Make your child component ExercisesList as functional component that only show the corresponding ExercisesList for every chapter not perform any rendering.
Like below:
const ExercisesList = (props) => {
const { exercises } = props;
return({
exercises.map(exercise, index) => renderExcercise(exercise, index)
})
}
const renderExcercise = (exercise, index) => {
return(
<View key={exercise.id}>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.props.showSelectedItemList(exercise.screenName, exercise.name)
}
>
<Image source={exercise.icon}/>
<View>
<Text>{exercise.name}</Text>
</View>
<Image source={arrow} />
</TouchableOpacity>
<View />
</View>
)
}
export default ExercisesList;
ExercisesList.propTypes = {
onPress: PropTypes.func,
exercises: PropTypes.arrayOf(PropTypes.object)
};

Input value is not seen completely, why?

So, almost everything works as it should, the problem is when I type something in input it does not update the redux state completely. Example: if I type ABC it will send that to server via axios.post() like AB... If I type BEER it will send BEE ... It does not see the last letter or if I choose auto complete text on my device, it does not see the entire word if it is the last thing in the input....
Any suggestions?
Thanks in advance.
class AddressScreen extends Component {
state = {
usersNickOrName: "",
usersAddress: "",
usersPhoneNumber: ""
};
componentWillUpdate() {
this.props.deliveryInfo(
this.state.usersNickOrName,
this.state.usersAddress,
this.state.usersPhoneNumber
);
}
onPressHandler = () => {
let uid = this.props.uid;
axios.post(
`.../users/${uid}/info.json`,
{
nameOrNick: this.props.name,
address: this.props.address,
phoneNum: this.props.phoneNum
}
);
this.props.navigator.pop();
};
render() {
return (
<View style={styles.container}>
<AnimatedForm delay={100} distance={10}>
<AnimatedInput
onChangeText={text => {
this.setState({ usersNickOrName: text });
}}
/>
<AnimatedInput
onChangeText={text => {
this.setState({ usersAddress: text });
}}
/>
<AnimatedInput
onChangeText={text => {
this.setState({ usersPhoneNumber: text });
}}
/>
<Animated.View style={styles.buttonView}>
<TouchableOpacity
style={styles.button}
onPress={this.onPressHandler}
>
<Text style={{ color: "#fff" }}>Dodaj Info</Text>
</TouchableOpacity>
</Animated.View>
</AnimatedForm>
</View>
);
}
}
const mapStateToProps = state => {
return {
name: state.usersNickOrName,
address: state.usersAddress,
phoneNum: state.usersPhoneNumber,
uid: state.userUid
};
};
const mapDispatchToProps = dispatch => {
return {
deliveryInfo: (usersName, usersAddress, phoneNum) =>
dispatch(deliveryInfo(usersName, usersAddress, phoneNum))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(AddressScreen);
You are currently using the old state in componentWillUpdate. Use the next state instead.
componentWillUpdate(nextProps, nextState) {
this.props.deliveryInfo(
nextState.usersNickOrName,
nextState.usersAddress,
nextState.usersPhoneNumber
);
}

How to send data from one screen to another screen in react native?

I am new to react native how can i send data from one screen to another screen using props in android not for ios my code is as below
Home.js
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
qwerty:{
data:[],
},
};
}
goPressed(navigate){
navigate("Product");
}
render() {
const { navigate } = this.props.navigation;
contents = this.state.qwerty.data.map((item) => {
return (
<View key={item.p1.id}>
<View>
<Text>{item.p1.content}</Text>
</View>
<View>
<TouchableHighlight onPress={() => this.goPressed(navigate)}>
<Text>
Go
</Text>
</TouchableHighlight>
</View>
</View>
);
});
return (
<ScrollView style={styles.container}>
{contents}
</ScrollView>
);
}
}
export default Home;
this is my home.js , I want pass data i.e {item.p1.content} to another screen i.e product.js so how can i do it what modification should i do?
Product.js
export default class Products extends Component {
static navigationOptions = {
title: "Products",
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>{item.p1.content}</Text>
</View>
);
}
}
Send data to other screen
this.props.navigation.navigate('Your Screen Name' , { YourParamsName: "Foo"});
Receive data from other screen
this.props.navigation.state.params.YourParamsName
One method is to simply pass the date you are storing in 'qwerty' as a props to the next scene.
In Home.js you can modify your goPressed method to be something like...
goPressed(navigate){
navigate("Product", {passedData: this.state.qwerty.item.p1.content});
}
Then in Product.js you will need to modify the code to
render() {
return (
<View style={{ flex: 1 }}>
<Text>{this.props.passedData}</Text>
</View>
);
}

Updating Parent Component via Child Component in React Native

I have a parent component and two child components. One of the child components is a form with an add button. I am able to capture the text when add button is pressed, but stuck when trying to pass that value to the parent component, update the array in parent component and re-render the view.
Parent Component:
var Tasks = ['Competitor Study','Content Plan','Write','Promote','Consumer Research']
//Build React Component
class MyTaskList extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.titleStyle}>
My Tasks
{"\n"}
({Moment().format("MMM Do YY")})
{"\n"}
</Text>
<AddTask />
{this.workitems()}
</View>
);
}
workitems() {
return (Tasks.map(function(workitem,i) {
return <ListItem key={i} workitem={workitem} />
}
)
);
}
}
Child component with the form
class AddTask extends Component {
constructor(props) {
super(props);
this.state = {
enterTask: 'Enter task'
};
}
onTaskTextChanged(event) {
this.setState({ enterTask: event.nativeEvent.text });
}
onAddPress() {
var newtask = this.state.enterTask;
console.log('new task - '+newtask);
}
render() {
return (
<View style={styles.addTask}>
<TextInput
style={styles.taskInput}
value={this.state.enterTask}
onChange={this.onTaskTextChanged.bind(this)}
placeholder='Enter task'/>
<TouchableHighlight style={styles.button}
onPress={this.onAddPress.bind(this)}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Add</Text>
</TouchableHighlight>
</View>
);
}
}
I would instead use state for this as using forceUpdate() is not recommended
From React docs:
Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your component "pure" and your application much simpler and more efficient.
(Based off of #1ven answer)
Parent Component:
//Build React Component
class MyTaskList extends Component {
constructor(props) {
super(props);
this.state = {
tasks: [
'Competitor Study',
'Content Plan',
'Write','Promote',
'Consumer Research'
]
}
}
handleAddTask(task) {
var newTasks = Object.assign([], this.state.tasks);
newTasks.push(task);
this.setState({tasks: newTasks});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.titleStyle}>
My Tasks
{"\n"}
({Moment().format("MMM Do YY")})
{"\n"}
</Text>
<AddTask onAddTask={this.handleAddTask.bind(this)} />
{this.workitems()}
</View>
);
}
workitems() {
return this.state.tasks.map(function(workitem,i) {
return <ListItem key={i} workitem={workitem} />
});
}
}
Child component with the form
class AddTask extends Component {
constructor(props) {
super(props);
this.state = {
enterTask: 'Enter task'
};
}
onTaskTextChanged(event) {
this.setState({ enterTask: event.nativeEvent.text });
}
onAddPress() {
var newtask = this.state.enterTask;
console.log('new task - '+newtask);
// Providing `newtask` variable to callback.
this.props.onAddTask(newtask);
}
render() {
return (
<View style={styles.addTask}>
<TextInput
style={styles.taskInput}
value={this.state.enterTask}
onChange={this.onTaskTextChanged.bind(this)}
placeholder='Enter task'/>
<TouchableHighlight style={styles.button}
onPress={this.onAddPress.bind(this)}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Add</Text>
</TouchableHighlight>
</View>
);
}
}
You should provide handleAddTask callback from parent to child component:
var Tasks = ['Competitor Study','Content Plan','Write','Promote','Consumer Research']
//Build React Component
class MyTaskList extends Component {
handleAddTask(task) {
// When task will be added, push it to array
Tasks.push(task);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.titleStyle}>
My Tasks
{"\n"}
({Moment().format("MMM Do YY")})
{"\n"}
</Text>
<AddTask onAddTask={this.handleAddTask} />
{this.workitems()}
</View>
);
}
workitems() {
return (
Tasks.map(function(workitem,i) {
return <ListItem key={i} workitem={workitem} />
})
);
}
}
Next, you should pass task from child component to this callback:
class AddTask extends Component {
constructor(props) {
super(props);
this.state = {
enterTask: 'Enter task'
};
}
onTaskTextChanged(event) {
this.setState({ enterTask: event.nativeEvent.text });
}
onAddPress() {
var newtask = this.state.enterTask;
console.log('new task - '+newtask);
// Providing `newtask` variable to callback.
this.props.onAddTask(newtask);
}
render() {
return (
<View style={styles.addTask}>
<TextInput
style={styles.taskInput}
value={this.state.enterTask}
onChange={this.onTaskTextChanged.bind(this)}
placeholder='Enter task'/>
<TouchableHighlight style={styles.button}
onPress={this.onAddPress.bind(this)}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Add</Text>
</TouchableHighlight>
</View>
);
}
}
That's it. Hope, it helps!

Categories