1
+ /** @packageDocumentation @reactapi @module react_hooks */
2
+
1
3
import * as React from 'react' ;
2
4
import { useCallback , useContext , useEffect , useMemo , useState } from 'react' ;
3
5
import { isString , StateDeclaration , TransitionOptions } from '@uirouter/core' ;
@@ -15,15 +17,15 @@ export interface LinkProps {
15
17
/** @hidden */
16
18
export const IncorrectStateNameTypeError = `The state name passed to useSref must be a string.` ;
17
19
18
- /** Gets all StateDeclarations that are registered in the StateRegistry. */
20
+ /** @hidden Gets all StateDeclarations that are registered in the StateRegistry. */
19
21
function useListOfAllStates ( router : UIRouterReact ) {
20
22
const initial = useMemo ( ( ) => router . stateRegistry . get ( ) , [ ] ) ;
21
23
const [ states , setStates ] = useState ( initial ) ;
22
24
useEffect ( ( ) => router . stateRegistry . onStatesChanged ( ( ) => setStates ( router . stateRegistry . get ( ) ) ) , [ ] ) ;
23
25
return states ;
24
26
}
25
27
26
- /** Gets the StateDeclaration that this sref targets */
28
+ /** @hidden Gets the StateDeclaration that this sref targets */
27
29
function useTargetState ( router : UIRouterReact , stateName : string , context : StateDeclaration ) : StateDeclaration {
28
30
// Whenever any states are added/removed from the registry, get the target state again
29
31
const allStates = useListOfAllStates ( router ) ;
@@ -33,13 +35,35 @@ function useTargetState(router: UIRouterReact, stateName: string, context: State
33
35
}
34
36
35
37
/**
36
- * A hook that helps create link to a state.
38
+ * A hook to create a link to a state.
39
+ *
40
+ * This hook returns link (anchor tag) props for a given state reference.
41
+ * The resulting props can be spread onto an anchor tag.
42
+ *
43
+ * The props returned from this hook are:
44
+ *
45
+ * - `href`: the browser URL of the referenced state
46
+ * - `onClick`: a mouse event handler that will active the referenced state
47
+ *
48
+ * Example:
49
+ * ```jsx
50
+ * function HomeLink() {
51
+ * const sref = useSref('home');
52
+ * return <a {...sref}>Home</a>
53
+ * }
54
+ * ```
37
55
*
38
- * This hook returns data for an sref (short for state reference)
56
+ * Example:
57
+ * ```jsx
58
+ * function UserLink({ userId, username }) {
59
+ * const sref = useSref('users.user', { userId: userId });
60
+ * return <a {...sref}>{username}</a>
61
+ * }
62
+ * ```
39
63
*
40
64
* @param stateName The name of the state to link to
41
65
* @param params Any parameter values
42
- * @param options Transition options
66
+ * @param options Transition options used when the onClick handler fires.
43
67
*/
44
68
export function useSref ( stateName : string , params : object = { } , options : TransitionOptions = { } ) : LinkProps {
45
69
if ( ! isString ( stateName ) ) {
0 commit comments