Skip to content

Commit

Permalink
add useTitle
Browse files Browse the repository at this point in the history
  • Loading branch information
Barry127 committed Nov 27, 2020
1 parent d633568 commit a78e66a
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 1 deletion.
33 changes: 33 additions & 0 deletions pages/docs/hooks/useTitle.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Meta } from 'docsComponents';

<Meta title="useTitle" />

# useTitle

useTitle sets document title when a title is passed.

## Signature

```ts
function useTitle(title?: string): void;
```

### Example

Set document title with useTitle.

```js live withRender
function TitleComponent() {
const [title, setTitle] = useState();
useTitle(title);

return (
<>
<H3>Type to set document title</H3>
<TextInput value={title} onChange={(ev) => setTitle(ev.target.value)} />
</>
);
}

render(<TitleComponent />);
```
3 changes: 2 additions & 1 deletion pages/docs/nav.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@
"useDarkMode": "/docs/hooks/useDarkMode",
"useFocus": "/docs/hooks/useFocus",
"useId": "/docs/hooks/useId",
"useOutline": "/docs/hooks/useOutline"
"useOutline": "/docs/hooks/useOutline",
"useTitle": "/docs/hooks/useTitle"
}
},
"Customizing": {
Expand Down
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './useFocus';
export * from './useId';
export * from './useOutline';
export * from './useTheme';
export * from './useTitle';
1 change: 1 addition & 0 deletions src/hooks/useTitle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useTitle } from './useTitle';
23 changes: 23 additions & 0 deletions src/hooks/useTitle/useTitle.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { renderHook } from '@testing-library/react-hooks';
import { useTitle } from './useTitle';

describe('useTitle', () => {
beforeEach(() => {
document.title = 'initial title';
});

it('sets title', () => {
renderHook(() => useTitle('Hello World'));
expect(document.title).toBe('Hello World');
});

it('does not change title when no title is passed', () => {
renderHook(() => useTitle());
expect(document.title).toBe('initial title');
});

it('does not change title when empty string is passed', () => {
renderHook(() => useTitle(''));
expect(document.title).toBe('initial title');
});
});
12 changes: 12 additions & 0 deletions src/hooks/useTitle/useTitle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useEffect } from 'react';

/**
* useTitle sets document title when a title is passed.
*/
export function useTitle(title?: string): void {
useEffect(() => {
if (title) {
document.title = title;
}
}, [title]);
}

0 comments on commit a78e66a

Please sign in to comment.