0.5.5 • Published 4 years ago
@tourepedia/react-hooks v0.5.5
React Hooks
Some helper react hooks
Install
npm install --save @tourepedia/react-hooks
Usage
useDidMount
Call a function on component's didMount Lifecycle
import { useDidMount } from "@tourepedia/react-hooks"
function App() {
useDidMount(() => {
// only called on mount
fetchTheData()
})
}
useDidUpdate
Call a function only in component's didUpdate Lifecycle.
import { useDidUpdate } from "@tourepedia/react-hooks"
function App({ count }) {
useDidUpdate(() => {
// called when the count changes
}, [count])
}
useOnce
Only call a function once in a component's Lifecycle
import { useOnce } from "@tourepedia/react-hooks"
function App() {
useOnce(() => {
// only called once
fetchTheData()
})
}
useEnforceFocus
Enforces focus to be contained in a container and return back to last focused element based on a condition
useEnforceFocus(
containerRef, // React.Ref: of the container
shouldBeFocused, // boolean: (true) to toggle the focus enforcement
config: {
autoFocus // boolean: (true) should the container be autoFocus
enforceFocus // boolean: (true) should return the focus to the last focused element
}
)
import { useRef, useState } from "react"
import { useEnforceFocus } from "@tourepedia/react-hooks"
function App() {
const containerRef = useRef()
const [shouldBeFocused, toggleShouldFocus] = useState(false)
// will focus the form container when shouldBeFocused is set to true
useEnforceFocus(containerRef, shouldBeFocused)
return (
<div>
<form className="container" ref={containerRef}>
<input type="email" autoFocus />
<button type="submit">Save</button>
</form>
<button onClick={() => toggleShouldFocus(!shouldBeFocused)}>
Toggle Focus
</button>
</div>
)
}