1

I am currently developing a package, which gives my React-widget responsiveness. The problem is, that the responsiveness does not depends on the viewport-width but on on the width of the widget-container-element.

Currently I am wrapping my <App> with a <ResponsiveProvider>. This provider subscribes to the windows.resize event and stores the format into the context's value.

All children elements get re-rendered if the format changes. That's fine.

Now, for show/hide components based on the current widget format, I just could implement a component, which accesses this context with contextType.

But I need a function, which I can use in any place of my application like: ResponsiveUtil.isSmall() or ResponsiveUtil.getCurrentFormat().

What would be the best approach to make the information (format) accessable via a function?

Thanks

1
  • I dont know for sure of if this can work, but the useContext hook comes to mind. Tho I dont even know if hooks are in RN yet. Commented Feb 14, 2019 at 21:26

1 Answer 1

1

I'm not sure if this would be the best approach, but it will work. You can set up a global event listener that will be dispatched each time the format changes in your component. I found a package here for the global events, but it wouldn't be hard to write your own either. Using react-native-event-listeners, it would look something like:

ResponsiveUtil.js

import { EventRegister } from 'react-native-event-listeners';

let format = {};

EventRegister.addEventListener('responsive-format-changed', data => {
    format = data;
});

const ResponsiveUtils = {
    getCurrentFormat() {
        return Object.assign({}, format);
    },
    isSmall() {
        //isSmall logic
    }
};

export default ResponsiveUtils;

Then, in your <ResponsiveProvider>, during the resize event, dispatch the new format when you update the context

ResponsiveProvider.js

import { EventRegister } from 'react-native-event-listeners';
//...Other component code
window.resize = () => {
    let format = calculateNewFormat();
    //update context...
    //dispatch new format
    EventRegister.emit('responsive-format-changed', format);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Hi! I had a similiar approach: I made the ResponsiveUtil to a Singleton and used it from the ResponsiveProvider and my components. This worked well but: The components do not re-render if they are not using the ResponsiveContext. So if a sete the static contextType in component (what I want to avoid), the components are re-rendering if the format-changes and can access the format via ResponsiveUtil.xy(). But if I remove the contextType, the components are not re-rendering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.