@rafaelolvr/ss-lib
v1.0.10
Published
A shareable library for React applications.
Readme
ss_lib
Library of utility hooks and helpers for React applications.
Hooks
useAudio
A hook to manage audio playback.
Signature:
const {
playing,
play,
pause,
toggle,
stop,
volume,
setVolume
} = useAudio(url: string, loop: boolean = false);Parameters:
url(string): The URL of the audio file.loop(boolean, optional): Whether the audio should loop. Default isfalse.
Return Values:
playing(boolean): Current playing state.play(function): Function to start playback.pause(function): Function to pause playback.toggle(function): Function to toggle between play and pause.stop(function): Function to stop playback and reset time to 0.volume(number): Current volume (0.0 to 1.0).setVolume(function): Function to set the volume.
Example:
import { useAudio } from "@rafaelolvr/ss-lib";
const MyComponent = () => {
const { play, pause, toggle } = useAudio("./sound.mp3");
return <button onClick={toggle}>Toggle Sound</button>;
};useObserve
A hook to listen for window messages (NUI events).
Signature:
useObserve<T>(eventName: string, handler: (data: T) => void);Parameters:
eventName(string): The name of the event to listen for.handler(function): Callback function to handle the event data.
Example:
import { useObserve } from "@rafaelolvr/ss-lib";
interface MyData {
action: string;
payload: any;
}
const MyComponent = () => {
useObserve<MyData>("myEvent", (data) => {
console.log("Received data:", data);
});
return <div>Listening for events...</div>;
};listen
A hook to add event listeners to the window or specific elements. It automatically cleans up the listener when the component unmounts.
Signature:
// For Window events
listen<K extends keyof WindowEventMap>(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element?: Window
);
// For HTMLElement events
listen<K extends keyof HTMLElementEventMap>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: HTMLElement
);Parameters:
eventName(string): The name of the event (e.g., 'keydown', 'click').handler(function): The event handler function.element(EventTarget, optional): The element to attach the listener to. Defaults towindow.
Example:
import { listen } from "@rafaelolvr/ss-lib";
const MyComponent = () => {
// Listen for keydown on window
listen("keydown", (event) => {
if (event.key === "Escape") {
console.log("Escape pressed");
}
});
return <div>Press Escape</div>;
};