0

I'm developing a common npm package with React's components for later usages in several projects. I've got default snackbar components and one wrapper component that will return a certain snackbar depending on snackbar's type provided to the wrapper's props. Here is my snackbar wrapper's code:

const TYPES = {
  [SNACKBAR_TYPES.SUCCESS]: SnackbarSuccess,
  [SNACKBAR_TYPES.ERROR]: SnackbarError,
  [SNACKBAR_TYPES.INFO]: SnackbarInfo,
  [SNACKBAR_TYPES.LOADING]: SnackbarLoading
}

const CustomSnackbars = props => {
  const CustomSnackbar = TYPES[props.snackbarType]

  if (!CustomSnackbar) {
    console.log('Invalid snackbar type was provided')
    return null
  }

  return (
    <CustomSnackbar {...props} />
  )
}

This wrapper will be used in projects for creating CustomSnackbars container. But here comes one problem that every project will probably define it's own snackbars with it's own snackbar type. And I don't want to put every snackbar that I will have later in my projects to my common module. Is it possible to somehow extend CustomSnackbars wrapper from the each projects's side, so this wrapper will have specific to each project's snackbar types in addition to default snackbar types?

1 Answer 1

1

Try to pass your additional TYPES by props:

CustomSnackbars.js (in common library)

const TYPES = {
  [SNACKBAR_TYPES.SUCCESS]: SnackbarSuccess,
  [SNACKBAR_TYPES.ERROR]: SnackbarError,
  [SNACKBAR_TYPES.INFO]: SnackbarInfo,
  [SNACKBAR_TYPES.LOADING]: SnackbarLoading
}

const CustomSnackbars = props => {
  const enhancedTypes = {...TYPES, ...props.userDefinedTypes};
  const CustomSnackbar = enhancedTypes[props.snackbarType]

  if (!CustomSnackbar) {
    console.log('Invalid snackbar type was provided')
    return null
  }

  return (
    <CustomSnackbar {...props} />
  )
}

Moreover, if you do not want to pass these userDefinedTypes to props in every instance of CustomSnackbars in your consumer project, you can create project specific CustomSnackbars, which will just render your common CustomSnackbars with userDefinedTypes in props.

ProjectSpecificCustomSnackbars.js (in your project)

const PROJECT_SPECIFIC_TYPES = {
  [SNACKBAR_TYPES.PROJECT_SUCCESS]: SnackbarProjectSuccess,
  [SNACKBAR_TYPES.PROJECT_INFO]: SnackbarProjectInfo
}

const ProjectSpecificCustomSnackbars = props => (
  <CustomSnackbars {...props} userDefinedTypes={PROJECT_SPECIFIC_TYPES} />
)

Sign up to request clarification or add additional context in comments.

Comments

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.