Responsive UIs in React Native

On the web it is – by now – obvious that you make your website responsive (*). Using a listener listening to the change event of the Dimensions API, it’s also possible to implement this kind of behaviour in React Native.

import {Component} from "react";
import {Dimensions} from "react-native";

export default class LogDimensionChanges extends Component {
    state = Dimensions.get("window");
    handler = dims => this.setState(dims);

    componentWillMount() {
        Dimensions.addEventListener("change", this.handler);
    }

    componentWillUnmount() {
      // Important to stop updating state after unmount
      Dimensions.removeEventListener("change", this.handler);
    }

    render() {
        const {width, height} = this.state.window;
        const mode = height > width ? "portrait" : "landscape";
        console.log(`New dimensions ${width}x${height} (${mode})`);
        return null;
    }
}

This logic is applied into the react-native-responsive-ui package, which provides you with a <MediaQuery /> component, ResponsiveStyleSheet class, etc.:

import React, {Component} from "react";
import {View} from "react-native";
import {MediaQuery} from "react-native-responsive-ui";

export default class Login extends Component {
    render(): React$Element<*> {
        return <View>
            <MediaQuery minHeight={450} orientation="portrait">
                <Logo />
            </MediaQuery>
        </View>;
    }
}

Responsive UIs in React Native →
react-native-responsive-ui

(*) I know, this site still uses a non-responsive WordPress theme … shame on me

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.