First, a helper method. The purpose of this is just to make sure we don't enter into an infinite loop when we pass the props to navigation.params inside componentDidUpdate--and to encapsulate smidge of logic involved in actually mapping the prop. This uses JSON.stringify to compare the props. Depending on what you're doing, you may need to substitute that bit with a more sophisticated comparison.
export function mapPropsToNavigationRouteParams(
props,
prevProps,
getPropsToMap,
) {
if (!props) return;
const propsToMap = getPropsToMap(props);
if (
!prevProps ||
JSON.stringify(getPropsToMap(prevProps)) !== JSON.stringify(propsToMap)
) {
props.navigation.setParams(getPropsToMap(props));
}
}
Then, in the component with the method above pulled in we can do something like this...
const getPropsToMapToNavigation = props => ({
myComponentProp: props.myComponentProp,
});
class MyComponent extends React.Component {
componentDidMount() {
mapPropsToNavigationRouteParams(
this.props,
null,
getPropsToMapToNavigation,
);
}
componentDidUpdate(prevProps) {
mapPropsToNavigationRouteParams(
this.props,
prevProps,
getPropsToMapToNavigation,
);
}
static navigationOptions = ({navigation}) => {
const {params} = navigation.state;
const myComponentProp = params ? params.myComponentProp : null;
// ...
}
Given the limitations of react-router, this is the best I could come up with. If you have a better solution, let me know!