Search code examples
androidiosreact-nativenative-base

programmatically retrieve Header component height - React Native


Using NativeBase, I added a Header component. Now, I want to programmatically retrieve the height of the header. How can I do this. The code for adding the Header is given below:

I tried using Dimensions.get('window') but it gives me the height of the entire view.

The code:

import React, {Component} from 'react-native';
import {Container, Header, Button, Title, Icon} from 'native-base';
​
export default class ThemeHeaderExample extends Component {
    render() {
        return (
                <Header>
                    <Button transparent />

                    <Title>Header</Title>

                </Header>
        );
    }
}

Solution

  • Sadly, NativeBase.Header does not expose Height.

    I faced the same problem and I dove into the code, I realized Height is harcoded in this way:

    toolbarHeight: platform === "ios" ? 64 : 56
    

    Take a look here at line 155. You will end up there following Header Component at line 300.

    Even though this might work, It does not seem to be something we might want to do, or at least, that fixed solution seems to be ugly.

    So, what I did was to create my own Header, which is pretty straight forward and easy since it is just a wrapper, and used "refs measure" function that allows us to get position and size. You can see an example here.

    Basically, It should look like this:

    render() {
        return (
          <View style={styles.container} ref="yourComponent">
            <TouchableOpacity onPress={this.measureYourComponent}>
              <Text>Measure it</Text>
            </TouchableOpacity>
          </View>
        );
    }
    
    measureYourComponent() {
        this.refs.yourComponent.measure((ox, oy, width, height, px, py) => {
            console.log("ox: " + ox); //Relative position
            console.log("oy: " + oy); //Relative position
            console.log("width: " + width);
            console.log("height: " + height);
            console.log("px: " + px); //Absolute position
            console.log("py: " + py); //Absolute position
          });
    }
    

    In my case, I needed to react from some parent depending on a child's size, so replace the OnPress handler for a Handler provided by its parent.

    In this way, despite you will need some more effort, you will have a solution more flexible and reusable.

    Let me know if there is something to clarify.