Back to Guides

Responsive Design

Guidance around Preshapes Responsive component, and responsive design with the Javascript matchMedia API.

Responsive Approach

Typically CSS media queries are used to change the layout and design, when hitting certain breakpoints. That approach does have its limitation and can get quite custom depending on different layouts. The limitations, for React, come from not every prop can be configured in CSS and the structure of a render method might need to widly differ passed the point of legible CSS.

The Responsive Component

Preshape has a Responsive component that uses the matchMedia Javascript API to listen to when specific breakpoints are hit. This allows greater control over what props are set and what and how a component is rendered. This also provides a way to keep the render functions generic, without needing to give elements specific classes to target them with CSS.
import React, { Component } from 'react';
import { Flex, Responsive, Text } from 'preshape';

class MyComponent extends Component {
  render() {
    return (
      <Responsive queries={ ['10rem', '20rem'] }>
        { (match) => (
          <Flex direction={ match('10rem') ? 'horizontal' : 'vertical' }>
                '10rem': <Text size="x2">Viewport is bigger than 10rem but less than 20rem</Text>,
                '20rem': <Text size="x3">Viewport is bigger than 20rem</Text>
              }) || (
                <Text size="x1">Viewport is less than 10rem</Text>
        ) }

Static Rendering and the Hydration stage

This approach does have its pitfall when hydrating statically rendered templates from build time or dynamic server side rendering.
Both of these types of static rendering happen before the viewport rending the React application are known. During Reacts hydration stage the initial template can differ from the one that has been optimised for that viewport. This can give the user a jarring experience if the application initialisation takes a long time and the templates widly differ.
It's best to keep entry points as similar across breakpoints as possible and/or the app initialisation time as quick as possible.
  • Check out this project on Github