Search code examples
react-nativereact-navigationreact-navigation-v5

React navigation Get stack navigator header height inside class component (without hooks)


I know it is possible to get stack header height with the following hook (V5):

import { useHeaderHeight } from '@react-navigation/stack';

Is there a workaround for a class component ? For the moment I am using a context consumer to get the height inside the render() function :

<HeaderHeightContext.Consumer>
                  {headerHeight => (   
    ...
    )}
</HeaderHeightContext.Consumer>

But I would like to have the headerHeight outside my render() function.


Solution

  • Have you tried in your component something like this:

    static contextType = HeaderHeightContext;
    
    componentDidMount() {
       console.log(this.context); // this is your height
    }
    

    From documentation:

    The contextType property on a class can be assigned a Context object created by React.createContext(). This lets you consume the nearest current value of that Context type using this.context