I want to set the title
of my screen to a specific value when I click a button on another screen.
So what I want to achieve at the end is the following. From my HomeScreen
I get to a ChangeScreen
where I can save the user profile. Now in that screen when the user submits its name
, that name should be shown in the header title for instance.
I still miss the part where the data is transferred from ChangeScreen
to App.js
.
I already found very similar question but I was not able to apply those solutions:
- Can't pass state to another component [react-native]
- How do I call setState from another Component in ReactJs
Find my Snack here.
App.js
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Home from './components/HomeScreen';
import Change from './components/ChangeScreen';
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
const Stacks = createStackNavigator();
class App extends React.Component {
state = {
newtitle : 'foo'
}
handleLoginnameChange = newtitle => {
this.setState({ newtitle })
}
render() {
return (
<NavigationContainer>
<Stacks.Navigator
headerMode="screen"
screenOptions={{
//headerTitle: this.state.newtitle,
//headerTitle: props => <Change {...props} />
}}
>
<Stacks.Screen
name="home"
component={Home}
options={
{
title: 'Home'
}
}
/>
<Stacks.Screen
name="change"
component={Change}
options={
{
title: 'Change'
}
}
/>
</Stacks.Navigator>
</NavigationContainer>
);
}
}
export default (App);
HomeScreen.js
import React from 'react'
import { Button, Text, View } from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
<View>
<Text>Hi, this is a test of change the title from another component</Text>
<Button title='To the Change title screen' onPress={() => this.props.navigation.navigate('change')}>Change</Button>
</View>
);
}
}
export default HomeScreen;
ChangeScreen.js
import React from 'react'
import { Button, Text, View } from 'react-native';
class ChangeScreen extends React.Component {
render() {
return (
<View>
<Text>Clicking this button will change the Header title to "TEST" and going back to Home.</Text>
<Button title='Save' onPress={() => this.props.navigation.navigate('home')}>Home</Button>
// on that button I need the setState or something similar like a onChange or onClick handler
</View>
);
}
}
export default ChangeScreen;