Skip to content

Commit

Permalink
Add a useSnackbar hook.
Browse files Browse the repository at this point in the history
  • Loading branch information
leMaik committed Jul 27, 2019
1 parent a6f8532 commit 7b51793
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,32 @@ import { SnackbarProvider } from 'material-ui-snackbar-provider'
</SnackbarProvider>
```

You can then display messages with the `withSnackbar` HOC and the injected `snackbar` prop in your components.
You can then display messages with the `useSnackbar` hook.

```js
import { useSnackbar } from 'material-ui-snackbar-provider'

export default function MyComponent (props) {
const snackbar = useSnackbar()

const handleSomething = () => {
snackbar.showMessage(
'Something happened!',
'Undo', () => handleUndo()
)
}

const handleUndo = () => {
// *snip*
}

return (
// *snip*
)
}
```

If you're not using React ^16.8.0 and our you can't use hooks (e.g. in a class component), you can use the `withSnackbar` HOC and the injected `snackbar` prop instead.

```js
import { withSnackbar } from 'material-ui-snackbar-provider'
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as SnackbarProvider } from './SnackbarProvider'
export { default as withSnackbar } from './withSnackbar'
export { default as useSnackbar } from './useSnackbar'
6 changes: 6 additions & 0 deletions src/useSnackbar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from 'react'
import SnackbarContext from './SnackbarContext'

export default function useSnackbar () {
return React.useContext(SnackbarContext)
}
35 changes: 35 additions & 0 deletions src/useSnackbar.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/* eslint-env jest */
import React from 'react'
import { mount } from 'enzyme'
import SnackbarContext from './SnackbarContext'
import useSnackbar from './useSnackbar'

describe('useSnackbar', () => {
it('injects the snackbar object', () => {
const dummySnackbarContext = {
showMessage: () => {}
}

function DummySnackbarProvider ({ children }) {
return (
<SnackbarContext.Provider value={dummySnackbarContext}>
{children}
</SnackbarContext.Provider>
)
}

let snackbar
const Component = function () {
snackbar = useSnackbar()
return null
}

mount(
<DummySnackbarProvider>
<Component />
</DummySnackbarProvider>
).find(Component)

expect(snackbar).toBe(dummySnackbarContext)
})
})

0 comments on commit 7b51793

Please sign in to comment.