Skip to content

Commit

Permalink
feat(components): expose sidebar context (#512)
Browse files Browse the repository at this point in the history
expose sidebar context that allows it to be used with the useContext hook.
This allows the side bar
context to be used in a simpler pattern that does not require the render props method of usage.
  • Loading branch information
nikilok authored Nov 27, 2019
1 parent ce944f4 commit 78a44b2
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/components/Sidebar/SidebarContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
import React, { createContext } from 'react';
import PropTypes from 'prop-types';

const SidebarContext = createContext();
const SidebarContext = createContext({
isSidebarOpen: false,
toggleSidebar: () => {}
});

const SidebarContextConsumer = SidebarContext.Consumer;

Expand Down Expand Up @@ -48,4 +51,4 @@ SidebarContextProvider.propTypes = {
children: PropTypes.node
};

export { SidebarContextProvider, SidebarContextConsumer };
export { SidebarContext, SidebarContextProvider, SidebarContextConsumer };
33 changes: 32 additions & 1 deletion src/components/Sidebar/SidebarContext.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,25 @@
* limitations under the License.
*/

import React from 'react';
import React, { useContext } from 'react';
import {
SidebarContext,
SidebarContextProvider,
SidebarContextConsumer
} from './SidebarContext';

const ToggleSidebarButton = () => {
const { toggleSidebar, isSidebarOpen } = useContext(SidebarContext);

return (
<button
data-testid="button"
onClick={toggleSidebar}
data-open={isSidebarOpen}
/>
);
};

describe('SidebarContext', () => {
it('should change Provider open state when using toggleSidebar', () => {
const { getByTestId } = render(
Expand All @@ -45,4 +58,22 @@ describe('SidebarContext', () => {

expect(buttonEl).toHaveAttribute('data-open', 'true');
});

it('should be able to consume context, along with useContext hook', () => {
const { getByTestId } = render(
<SidebarContextProvider>
<ToggleSidebarButton />
</SidebarContextProvider>
);

const buttonElement = getByTestId('button');

expect(buttonElement).toHaveAttribute('data-open', 'false');

act(() => {
fireEvent.click(buttonElement);
});

expect(buttonElement).toHaveAttribute('data-open', 'true');
});
});
3 changes: 2 additions & 1 deletion src/components/Sidebar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@

import Sidebar from './Sidebar';
import {
SidebarContext,
SidebarContextProvider,
SidebarContextConsumer
} from './SidebarContext';

export default Sidebar;
export { SidebarContextProvider, SidebarContextConsumer };
export { SidebarContext, SidebarContextProvider, SidebarContextConsumer };

0 comments on commit 78a44b2

Please sign in to comment.