Updating State of Parent component from Child Component (Tab Navigator) - javascript

I am new to React and React Native and I am trying to build an cooking recipe app. I am trying to update my dish state in DishTabNavigator.js from DishIngredients.js so that I can send the data to firebase from DishTabNavigator.js, however I do not know how I can update the state. I tried lifting the state up but I couldn't do it. Been stuck on this for a day now. Any help would be appreciated
DishTabNavigator.js
const Tab = createMaterialTopTabNavigator();
export default function MyTabs({ navigation }) {
const [dish, setDish] = useState([{ ingredients: [] }]);
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity style={styles.iconright}>
<Text>Send dish to Firebase</Text>
<FontAwesome name="save" size={24} color="black" />
</TouchableOpacity>
),
});
});
return (
<Tab.Navigator>
<Tab.Screen
name="Ingredient"
component={DishIngredients}
ingredients={dish}
/>
</Tab.Navigator>
);
}
DishIngredients.js
class DishIngredients extends Component {
constructor(props) {
super(props);
this.state = {
ingredients: [],
textInput: [],
};
//Add TextInput
addTextInput = (index) => {
let textInput = this.state.textInput;
textInput.push(
<TextInput
style={styles.textInput}
onChangeText={(text) => this.addValues(text, index)}
/>
);
this.setState({ textInput });
};
//Function to add values into the states
addValues = (text, index) => {
let dataArray = this.state.ingredients;
let checkBool = false;
if (dataArray.length !== 0) {
dataArray.forEach((element) => {
if (element.index === index) {
element.text = text;
checkBool = true;
}
});
}
if (checkBool) {
this.setState({
ingredients: dataArray,
});
} else {
dataArray.push({ text: text, index: index });
this.setState({
ingredients: dataArray,
});
}
};
//function to console the output
getValues = () => {
console.log("Data", this.state.ingredients);
this.props.ingredients = this.state.ingredients;
console.log(this.props.ingredients);
};
render() {
return (
<View>
<View style={styles.icon}>
<View style={{ margin: 10 }}>
<TouchableOpacity>
<Ionicons
name="add"
size={24}
color="black"
onPress={() => this.addTextInput(this.state.textInput.length)}
/>
</TouchableOpacity>
</View>
<View style={{ margin: 10 }}>
<Button title="Remove" onPress={() => this.removeTextInput()} />
</View>
</View>
{this.state.textInput.map((value) => {
return value;
})}
<Button title="Get Values" onPress={() => this.getValues()} />
</View>
);
}
}
export default DishIngredients;

You could use React Context
const DishContext = React.createContext({
dish: [],
setDish: () => {},
});
export const useDishContext = () => React.useContext(DishContext);
export const AppDishProvider = ({children}) => {
const [dish, setDish] = useState([{ingredients: []}]);
const defaultDish = {
dish,
setDish,
};
return (
<DishContext.Provider value={defaultDish}>{children}</DishContext.Provider>
);
};
Then
/** Wrap your TabNavigator with AppDishProvider */
<AppDishProvider>
<YourTabNavigator />
</AppDishProvider>
Then
/**
* In DishIngredients, or your TabNavigator...
* You get access to dish-state, and setDish using your
* custom-hook `useDishContext`
*/
const { dish, setDish } = useDishContext();
And if you're using class-based component
class DishIngredient extends React.Component {
static contextType = DishContext;
/**
* Current context-value could be accessed by
* `this.context`
*/
render() {
const {dish, setDish} = this.context;
/** .... */
}
}
Assuming you're not having redux wired in your app... ReactContext is your way to go...

Without changing a lot in your current code you can do like this
const addIngredient = (ingredient) => {
// TODO: ingredient
};
return (
<Tab.Navigator>
<Tab.Screen name="Ingredient">
{(props) => (
<DishIngredients
{...props}
ingredients={dish}
addIngredient={addIngredient}
/>
)}
</Tab.Screen>
</Tab.Navigator>
);
As you see there is a function addIngredient (You can rename as you wish) that will be introduced as prop in DishIngredients like this.props.addIngredient(<Your Ingredient text>).
ReactContext also a nice solution above but I think, this will force your app re-render every time your context changes. It might impact on your performance.

Related

react native random background image

I am learning react native at the moment, I got my random background image to work but there is a bug now and I have no idea how to fix it easily, it now changes background everytime I do anything in app.
Main idea was to change image if app opens I added video what seems to be problem at the moment. Somehow background is not changeing when I update my task.
https://www.youtube.com/watch?v=JkAfe6BDZYg&feature=youtu.be&ab_channel=TheMrMaarek
const { height, width } = Dimensions.get("window");
const randomImages = [
require('./images/talv.jpg'),
require('./images/kevad.jpg'),
require('./images/suvi.jpg'),
require('./images/sügis.jpg'),
];
export default class App extends React.Component {
state = {
newToDo: "",
loadedToDos: false,
toDos: {}
};
componentDidMount = () => {
this._loadedToDos();
};
render() {
const { newToDo, loadedToDos, toDos } = this.state;
console.log(toDos);
if (!loadedToDos) {
return <AppLoading />;
}
return (
<ImageBackground source={randomImages[Math.floor(Math.random()*randomImages.length)]} style={styles.container}>
<StatusBar barStyle="light-content" />
<Text style={styles.title}>MS ToDo App</Text>
<View style={styles.card}>
<TextInput
style={styles.input}
placeholder={"Add new task here..."}
value={newToDo}
onChangeText={this._controlNewToDo}
placeholderTextColor={"black"}
returnKeyType={"done"}
autoCorrect={false}
onSubmitEditing={this._addToDo}
underlineColorAndroid={"transparent"}
/>
<ScrollView contentContainerStyle={styles.toDos}>
{Object.values(toDos)
.sort((a, b) => {
return a.createdAt - b.createdAt;
})
.map(toDo => (
<ToDo
key={toDo.id}
deleteToDo={this._deleteToDo}
uncompleteToDo={this._uncompleteToDo}
completeToDo={this._completeToDo}
updateToDo={this._updateToDo}
{...toDo}
/>
))}
</ScrollView>
</View>
</ImageBackground>
you want to just randomize the image in componentDidMount,
state = {
newToDo: "",
loadedToDos: false,
toDos: {},
currentImage: null,
};
...
componentDidMount = () => {
this._loadedToDos();
this.currentImage = randomImages[Math.floor(Math.random()*randomImages.length)];
};
...
<ImageBackground source={this.currentImage} style={styles.container}>

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)
};

react native redux state update but not rendering in a component

I have 2 components named A and B, In B I have a list of Languages to be selected and updated in component A. I am using Redux for state management when I change the Language from the list I can see that the states are updated(using redux-logger to get logs). But the problem is when I go back to Component A using react-navigation the updated state value is not updated I can see only the old value of state only
ScreenA.js
class ScreenA extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedLanguage: this.props.state.defaultLangName
}
}
render(
return (
<Container>
<Content style={{ backgroundColor: item.backgroundColor }}>
<View style={styles.logoContainer}>
<Text>test page</Text>
</View>
<View style={styles.cardParent}>
<View style={styles.card}>
<Item style={styles.listItem}>
<Button transparent style={styles.contentChecked} onPress={() => this._openLang()}>
<Text style={styles.listbtn}>{this.state.selectedLanguage}</Text>
<Icon name='ios-arrow-forward' style={styles.iconChecked}/>
</Button>
</Item>
</View>
</View>
</Content>
</Container>
);
)
}
export default connect(
state => ({ state : state.introauthenticate }),
dispatch => ({
actions: bindActionCreators(introActions, dispatch)
})
)(ScreenA);
ScreenB.js
class ScreenB extends Component {
constructor(props){
super(props);
this.state = {
langChecked: '0'
};
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#999",
}}
/>
);
}
_selectLanguage (val, name){
this.setState({ langChecked: val });
this.props.actions.changeLanguage(val,name, this.props.navigation.navigate);
//this.props.navigation.navigate('Intro');
}
renderItem = (item )=> {
return(
<TouchableHighlight
style={styles.boxSelect}
underlayColor="transparent"
onPress={() => this._selectLanguage(item.Value, item.Name)}
>
<View style={styles.contentChecked}>
<Text style={styles.item} > {item.Name} </Text>
{this.state.langChecked === item.Value && <Icon name="ios-checkmark-circle" style={styles.iconChecked}/>}
</View>
</TouchableHighlight>
)
}
render() {
return (
<Container>
<Header>
<Left>
<Button transparent onPress={() => this.props.navigation.goBack()}>
<Icon name='ios-arrow-back' />
</Button>
</Left>
<Body>
<Title>Languages</Title>
</Body>
<Right />
</Header>
<Content>
<FlatList
data={ langs }
keyExtractor={(item) => item.Value}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => this.renderItem(item)}
/>
</Content>
</Container>
);
}
}
export default connect(
state => ({ state: state.introauthenticate }),
dispatch => ({
actions: bindActionCreators(introActions, dispatch)
})
)(ScreenB);
reducer.js
export const CHANGE_LANGUAGE = "CHANGE_LANGUAGE";
export function changeLanguage(langValue,langName,navigateTo) { // Fake authentication function
return async dispatch => {
try {
if (langValue && langName) { //If the email and password matches
const session = { langValue : langValue,langName:langName } // Create a fake token for authentication
setTimeout(() => { // Add a delay for faking a asynchronous request
dispatch(setLanguage(session)) // Dispatch a successful sign in after 1.5 seconds
navigateTo('Intro') // If successfull login navigate to the authenticated screen
}, 1500)
}
} catch (err) { // When something goes wrong
console.log(err)
}
};
}
function setLanguage(lang){
return {
type: types.CHANGE_LANGUAGE,
data: {
lang: lang
}
};
}
const initialsliderState = {
defaultLang:'en',
defaultLangName:'English',
};
export default function introauthenticate(state = initialsliderState, action = {}) {
switch (action.type) {
case types.CHANGE_LANGUAGE:
return {
...state,
defaultLang: action.data.lang.langValue,
defaultLangName: action.data.lang.langName,
};
default:
return state;
}
}
Logger:
LOG %c prev state "introauthenticate": {"defaultLang": "nl", "defaultLangName": "Deutsch", "isAuthSlider": false, "requestingsliderRestore": false}
LOG %c action {"data": {"lang": {"langName": "English", "langValue": "en"}}, "type": "CHANGE_LANGUAGE"}
LOG %c next state "introauthenticate": {"defaultLang": "en", "defaultLangName": "English", "isAuthSlider": false, "requestingsliderRestore": false}}
You are initializing the state of ScreenA with a value passed as a prop and never update it. As you are using redux to store the current language you do not need any state in ScreenA. When you connect a component you pass it the relevant data from your store as props. It seems like you are trying to "override" the state by passing it in as state but that does not update the state as it will be in this.props.state rather then in this.state. What you need to do is to just pass the language as a prop to ScreenA:
export default connect(
state => ({ selectedLanguage : state.introauthenticate.defaultLang }),
dispatch => ({
actions: bindActionCreators(introActions, dispatch)
})
)(ScreenA);
and then read the selected language from props:
<Text style={styles.listbtn}>{this.props.selectedLanguage}</Text>
When you update your store the component will re-render with the new language. You do not need any additional state in the component itself for data that you have in your redux store.

How to pass the props from parent to child to child of child?

I want to pass the props from App.js(parent) to CommentItem.js(child) to Button.js(child of child),
but the props is empty in Button,js(child of child)'s component.
App.js(parent) to CommentItem.js(child)
I pushed mainuser: this.state.head to FlatList, and the props(mainuser) passed by renderItem={({ item }) => <CommentItem {...item}
And, CommentItem.js(child) received mainuser by the code below.
const {
head,
text,
created,
mainuser,
subuser,
} =
CommentItem.js(child) to Button.js(child of child)
I thought props was pased to Button by ,
and Button(child of child) received the props by the code below.
const {
mainuser,
} = this.props;
However, props id empty in Button.js(child of child).
#
Are there any problems of my code?
Could you give some advice please?
App.js(parent)
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
head: [],
list: [],
};
}
_onPress = (text) => {
const list = [].concat(this.state.list);
list.push({
key: Date.now(),
text: text,
done: false,
mainuser: this.state.head,
});
this.setState({
list,
});
}
render() {
const {
head,
list,
} = this.state;
var data = [["User1", "User2", "User3"],];
return (
<View style={styles.container}>
<View style={styles.dropdownHeader}>
<View style={styles.dropdown}>
<DropdownMenu
style={{flex: 1}}
bgColor={'white'}
tintColor={'#666666'}
activityTintColor={'green'}
handler={(selection, row) => this.setState({head: data[selection][row]})}
data={data}
>
</DropdownMenu>
</View>
</View>
<Text>To Do</Text>
<View style={styles.postinput}>
<CommentInput onPress={this._onPress} />
</View>
</View>
<View style={styles.CommentListContainer}>
<FlatList
/*inverted*/
style={styles.CommentList}
data={list}
renderItem={({ item }) => <CommentItem {...item} /> }
/>
</View>
);
}
}
CommentItem.js(child)
const CommentItem = (props) => {
const {
head,
text,
created,
mainuser,
subuser,
} = props;
return (
<View style={styles.container}>
<View style={styles.left}>
<Text style={styles.text}>{text}</Text>
</View>
<View style={styles.function}>
<Button {...mainuser} />
</View>
</View>
);
}
Button.js(child of child)
export default class ApplauseButton extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
const {
mainuser,
} = this.props;
return (
<View style={styles.container}>
<Text>{mainuser}</Text>
</View>
);
}
}
If you want to access mainuser as a prop, then you've to pass it as <Button mainuser={mainuser} />.
As it stands, you're spreading the contents of mainuser.
as per your code it seems that main user is array,
this.state = {
head: [],//array
list: [],
};
....
list.push({
key: Date.now(),
text: text,
done: false,
mainuser: this.state.head,// main user should be array
});
so you need to give prop name also in <Button />
like this
<Button mainuser={mainuser} />

Pass state through Navigator

I'm using the React Native core Navigator component but having trouble figuring out how to pass data between components when pressing buttons in the Navigation Bar. Here is some example code of the setup that I have.
const NavigationBarRouteMapper = {
Title: (route, navigator) => {
let title;
switch (route.component.displayName) {
case 'FirstScreen':
title = 'First Screen';
break;
}
return (
<Text>
{title}
</Text>
)
},
LeftButton: (route, navigator) => {
let onButtonPress, buttonTitle;
switch (route.component.displayName) {
case 'SecondScreen':
buttonTitle = 'Close';
onButtonPress = () => navigator.pop();
break;
}
return (
<TouchableOpacity
onPress={onButtonPress}>
<Text>
{buttonTitle}
</Text>
</TouchableOpacity>
)
},
RightButton: (route, navigator) => {
let onButtonPress, buttonTitle;
switch (route.component.displayName) {
case 'SecondScreen':
buttonTitle = 'Save';
onButtonPress = () => {}; // #TODO Call onButtonPress in SecondScreen component
break;
}
return (
<TouchableOpacity
onPress={onButtonPress}>
<Text>
{buttonTitle}
</Text>
</TouchableOpacity>
);
}
};
const App = React.createClass({
renderScene(route, navigator) {
return <route.component navigator={navigator} {...route.props} />;
},
render() {
return (
<Navigator
style={styles.appContainer}
initialRoute={{component: SplashScreen}}
renderScene={this.renderScene}
navigationBar={
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
/>
}
/>
);
}
});
const FirstScreen = React.createClass({
onButtonPress() {
this.props.navigator.push({component: SecondScreen});
},
render() {
return (
<View>
<TouchableHighlight onPress={this.onButtonPress}>
<Text>
Click Me
</Text>
</TouchableHighlight>
</View>
);
}
});
const SecondScreen = React.createClass({
getInitialState() {
return {
input: ''
}
},
onButtonPress() {
if (this.state.input.length) {
// Do something with this.state.input such as POST to remote API
this.props.navigator.pop();
}
},
render() {
return (
<View style={styles.container}>
<TextInput
onChangeText={(input) => this.setState({input})}
value={this.state.input}
/>
</View>
);
}
});
You can see from the comments that I have a value stored in the state of SecondScreen that I want to do something with when someone hits the Save button. Any ideas?
In your renderScene function, while returning 'route.component' you can pass props and read them in the component.

Categories