Reputation: 1821
I have a react component class that declares a custom react-navigation header via the static navigationOptions function which react-navigation then calls automatically. The problem is, I want to render the header conditionally based on props passed to the component rather than simply props passed in as parameters to the route. I can't simply set them on componentDidMount, since the props I'm referencing change after the component it mounted and I need those to trickle into the header.
I figured out a way to do it and thought I'd post it here.
Upvotes: 0
Views: 876
Reputation: 1821
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!
Upvotes: 1