I just create two library (Theme and Snackbar), those library can be install as a standalone package, but now I want to optionally support some feature in case a project installing two of my library.
for example
App.js
import { SnackbarProvider } from 'myLibrary/snackbar';
import { ThemeProvider } from 'myLibrary/theme';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Routes from './Routes';
const App = () => {
return (
);
};
App.displayName = 'App';
export default App;
above code represent a project code that use both of my library (myLibrary/snackbar and myLibrary/theme)
and to access the theme within the project I've provided a hook called useTheme.
and now I want to enhanced myLibrary/snackbar library to reference myLibrary/theme setup like a color, font, etc.
How do i conditionally use useTheme within myLibrary/snackbar?
Snackbar.js
import React from 'react';
import {View, Text} from 'react-native';
// import { useTheme } from 'myLibrary/theme';
// throw error Unable to resolve module myLibrary/theme from /mypath/snackbar.js:
// myLibrary/theme could not be found within the project or in these directories:
const useTheme = await import("myLibrary/theme")
.then((module) => module.useTheme || null)
.catch((err) =>
console.log("π Snackbar.js:3 π | π§ err π§ | π", err)
);
const Snackbar = props => {
// use color from `useTheme` or fallback to default color
// conditionally use hook if exist
const {color} = useTheme()
return (
Snackbar Component
);
};
export default Snackbar;