add useTitle

This commit is contained in:
Dawid Wysokiński 2020-11-07 13:26:24 +01:00
parent 5b1a5968c8
commit fa17bf1a84
6 changed files with 43 additions and 4 deletions

View File

@ -1,5 +1,7 @@
export const DEFAULT_LANGUAGE = process.env.DEFAULT_LANGUAGE ?? 'en';
export const NAME = 'TWHelp';
export const SERVER_STATUS = {
CLOSED: 'closed',
OPEN: 'open',

View File

@ -1,15 +1,18 @@
import React from 'react';
import useTitle from '@libs/useTitle';
import useStyles from './styles';
import { INDEX_PAGE } from '@config/namespaces';
import { Container, Toolbar } from '@material-ui/core';
import Header from './components/Header/Header';
import ServerSelection from './components/ServerSelection/ServerSelection';
import Footer from './components/Footer/Footer';
import { useTranslation } from 'react-i18next';
export default function IndexPage() {
const classes = useStyles();
const { t } = useTranslation(INDEX_PAGE);
useTitle(t('title'));
return (
<div>
<Header />

View File

@ -2,7 +2,7 @@ import React from 'react';
import { useQueryParams, StringParam, withDefault } from 'use-query-params';
import { useDebouncedCallback } from 'use-debounce';
import { useTranslation } from 'react-i18next';
import { TWHELP } from '@config/app';
import { TWHELP, NAME } from '@config/app';
import * as NAMESPACES from '@config/namespaces';
import useStyles from './styles';
@ -59,7 +59,7 @@ export default function Header() {
</div>
<Hidden xsDown implementation="css">
<Link href={TWHELP} underline="none">
<Button>TWHelp</Button>
<Button>{NAME}</Button>
</Link>
</Hidden>
</Toolbar>

View File

@ -1,4 +1,5 @@
const translations = {
title: 'Home',
header: {
search: 'Search',
},

View File

@ -1,4 +1,5 @@
const translations = {
title: 'Strona główna',
header: {
search: 'Szukaj',
},

32
src/libs/useTitle.ts Normal file
View File

@ -0,0 +1,32 @@
import { useRef, useEffect } from 'react';
import { NAME } from '@config/app';
export interface UseTitleOptions {
restoreOnUnmount?: boolean;
}
const DEFAULT_USE_TITLE_OPTIONS: UseTitleOptions = {
restoreOnUnmount: false,
};
function useTitle(
title: string,
options: UseTitleOptions = DEFAULT_USE_TITLE_OPTIONS
) {
const prevTitle = useRef(document.title);
useEffect(() => {
document.title = `${title} | ${NAME}`;
if (options && options.restoreOnUnmount) {
return () => {
document.title = prevTitle.current;
};
}
return () => {
document.title = NAME;
};
}, [title, options]);
}
export default typeof document !== 'undefined'
? useTitle
: (_title: string) => {};