Reputation: 3041
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
Upvotes: 1
Views: 725
Reputation: 728
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);
};
Upvotes: 1