Skip to content

onQueryStateChange callback #94

@olistic

Description

@olistic

This is a feature proposal.

Hey! I really enjoy the declarative approach of react-media, but I just hit a wall in my use case where having a way of doing some imperative programming would really help.

The problem

When the width is enough, my screen is horizontally split in two. To the left, I have component Code and to the right I have two tabs with components Readme and Play. Just one tab can be active at a time, and which one it is is tracked in the component's state:

screen shot 2018-07-26 at 16 39 52

Now, when the width is not enough, I don't split the screen and instead convert Code into another tab:

screen shot 2018-07-26 at 16 40 56

The problem is that, when the width of the screen changes (because of orientation change, for example), if tab Code was active and then the tab ceases to exist, I end up with something like this:

screen shot 2018-07-26 at 16 41 13

I'd like to be able to modify the state upon a media query state change, to be able to change the active tab.

My proposal

Add an onQueryStateChange callback as a prop to the <Media> component, so imperative stuff can be done there. onQueryStateChange would receive the matches state as a parameter.

In my use case, that would allow me to do:

class MyComponent extends React.Component {
  state = {
    activeTab: 'README';  // Active tab defaults to 'README'.
  };

  handleQueryStateChange = e => { // e is a MediaQueryListEvent instance.
    // If 'CODE' was the active tab and it would cease to exist,
    // make 'README' the active tab.
    if (this.state.activeTab === 'CODE' && !e.matches) {
      this.setState({ activeTab: 'README' });
    }
  };

  render() {
    return (
      <Media
        query={...}
        onQueryStateChange={this.handleQueryStateChange}
      >
        ...
      </Media>
    );
  }
}

If this is something you would consider adding to react-media, I'm happy to work on a PR for it. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions