re-title
v1.0.1
Published
A React context-based component for dynamically updating document title
Maintainers
Readme
re-title
A lightweight React context-based library for dynamically managing the document title in React applications.
Features
- Simple API to update document title
- Context-based title management
- Custom hook for programmatic title updates
- TypeScript support
- Minimal dependencies
Installation
Install the package via npm:
npm install re-titleOr via yarn:
yarn add re-titleUsage
1. Wrap your app with ReTitleProvider
Wrap your application or a portion of it with the ReTitleProvider component to provide title management context.
import { ReTitleProvider } from 're-title';
function App() {
return (
<ReTitleProvider defaultTitle="My App">
<YourApp />
</ReTitleProvider>
);
}2. Set titles with ReTitle component
Use the ReTitle component to declaratively set the document title.
import { ReTitle } from 're-title';
function HomePage() {
return (
<div>
<ReTitle title="Home Page" />
<h1>Welcome to the Home Page</h1>
</div>
);
}3. Update titles programmatically with useReTitle hook
Use the useReTitle hook to update the title programmatically.
import { useReTitle } from 'reસ
re-title';
function DynamicTitleComponent() {
const setTitle = useReTitle();
const handleClick = () => {
setTitle('New Title');
};
return (
<button onClick={handleClick}>Change Title</button>
);
}API
ReTitleProvider
Props:
children: The React components to be wrapped (required)defaultTitle: The default document title (optional, defaults to empty string)
ReTitle
Props:
title: The title to set for the document (required)
useReTitle
Hook that returns a function to programmatically set the document title. Must be used within a ReTitleProvider.
Notes
- Ensure
ReTitleanduseReTitleare used within aReTitleProvider, or a console error will be logged. - The library updates the
document.titlewhenever thetitleprop or the result ofuseReTitlechanges.
Example
A complete example:
import { ReTitleProvider, ReTitle, useReTitle } from 're-title';
function Counter() {
const [count, setCount] = useState(0);
const setTitle = useReTitle();
useEffect(() => {
setTitle(`Count: ${count}`);
}, [count, setTitle]);
return (
<div>
<ReTitle title={`Counter App - ${count}`} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
return (
<ReTitleProvider defaultTitle="My Counter App">
<Counter />
</ReTitleProvider>
);
}License
MIT
