Reputation: 1572
I'm trying to implement a deletePost button, but I'm struggling to pass it into my header component. Here's the
export class PostScreen extends Component {
// Custom headerTitle component.
static navigationOptions = ({ navigation }) => {
const { params } = navigation.state;
return { headerTitle: <PostTitle {...params} handleDelete={this.handleDelete}/> }
};
handleDelete = async (id) => {
const { deletePost } = this.props;
const token = await AsyncStorage.getItem('token');
deletePost(token, id);
}
render() {
This does'nt seem to be the right way to pass it in. What's the correct way? I can't find anything in the docs.
Upvotes: 3
Views: 7654
Reputation: 157
in your component did mount use an arrow function as below and the function won't be called when the component first mount.
componentDidMount() {
this.props.navigation.setParams({ handleDelete: (() => this.handleDelete())
});
Upvotes: 0
Reputation: 28539
As you are using react-navigation
then this is how you set a function in the header component.
componentDidMount
set the function as a param using setParam
getParam
in your navigation header.This is how it would look in a very simple component.
export default class Screen1 extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params } = navigation.state; // this is included because you had added it and you may require the params in your component
return {
headerTitle: <PostTitle {...params} handleDelete={navigation.getParam('handleDelete')} />, // grab the function using getParam
};
};
handleDelete = () => {
alert('delete')
}
// set the function as a param in your componentDidMount
componentDidMount() {
this.props.navigation.setParams({ handleDelete: this.handleDelete });
}
render() {
return (
<View style={styles.container}>
<Text>Screen1</Text>
</View>
)
}
}
Then in your PostTitle
component you can use the function that you just passed by calling this.props.handleDelete
Here is a snack that shows the basic functionality https://snack.expo.io/@andypandy/functions-in-a-navigation-header
You can read more about setting functions in the navigation header here
Upvotes: 9