Skip to content
This repository has been archived by the owner on Feb 8, 2020. It is now read-only.

Commit

Permalink
feat: add a setOptions function and useOptions hook
Browse files Browse the repository at this point in the history
In React Navigation, the screen options can be specified statically. If you need to configure any options based on props and state of the component, or want to update state and props based on some action such as tab press, you need to do it in a hacky way by changing params. it's way more complicated than it needs to be. It also breaks when used with HOCs which don't hoist static props, a common source of confusion.

This PR adds a `setOptions` API to be able to update options directly without going through params, and an `useOptions` hook to make it easier to set them.
  • Loading branch information
satya164 committed Jul 22, 2019
1 parent 62f4047 commit 8a09d94
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 16 deletions.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,30 @@ A render callback which doesn't have such limitation and is easier to use for th

The rendered component will receives a `navigation` prop with various helpers and a `route` prop which represents the route being rendered.

## Setting screen options

In React Navigation, screen options can be specified in a static property on the component (`navigationOptions`). This poses few issues:

- It's not possible to configure options based on props, state or context
- To update the props based on an action in the component (such as button press), we need to do it in a hacky way by changing params
- It breaks when used with HOCs which don't hoist static props, which is a common source of confusion

Instead of a static property, we expose a hook to configure screen options:

```js
function Selection() {
const [selectedIds, setSelectedIds] = React.useState([]);

useOptions({
title: `${selectedIds.length} items selected`,
});

return <SelectionList onSelect={id => setSelectedIds(ids => [...ids, id])} />;
}
```

This allows options to be changed based on props, state or context, and doesn't have the disadvantages of static configuration.

## Type-checking

The library exports few helper types. Each navigator also need to export a custom type for the `navigation` prop which should contain the actions they provide, .e.g. `push` for stack, `jumpTo` for tab etc.
Expand Down Expand Up @@ -182,4 +206,16 @@ And then we can use it:
</Stack.Navigator>
```

To provide type-checking in the `useOptions` hook, we can provide it a type parameter:

```ts
function Profile({ userId }: Props) {
useOptions<StackNavigationOptions>({
title: `${userId}'s profile`,
});

// Content
}
```

Unfortunately it's not possible to verify that the type of children elements are correct since [TypeScript doesn't support type-checking JSX elements](https://github.com/microsoft/TypeScript/issues/21699).
48 changes: 33 additions & 15 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ import {
PartialState,
NavigationProp,
RouteProp,
useOptions,
} from '../src';
import StackNavigator, { StackNavigationProp } from './StackNavigator';
import StackNavigator, {
StackNavigationProp,
StackNavigationOptions,
} from './StackNavigator';
import TabNavigator, { TabNavigationProp } from './TabNavigator';

type StackParamList = {
Expand Down Expand Up @@ -65,20 +69,34 @@ const Second = ({
StackNavigationProp<StackParamList>,
NavigationProp<TabParamList>
>;
}) => (
<div>
<h1>Second</h1>
<button
type="button"
onClick={() => navigation.push('first', { author: 'Joel' })}
>
Push first
</button>
<button type="button" onClick={() => navigation.pop()}>
Pop
</button>
</div>
);
}) => {
const [count, setCount] = React.useState(0);

React.useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);

return () => clearInterval(timer);
}, []);

useOptions<StackNavigationOptions>({
title: `Count ${count}`,
});

return (
<div>
<h1>Second</h1>
<button
type="button"
onClick={() => navigation.push('first', { author: 'Joel' })}
>
Push first
</button>
<button type="button" onClick={() => navigation.pop()}>
Pop
</button>
</div>
);
};

const Fourth = ({
navigation,
Expand Down
14 changes: 13 additions & 1 deletion src/SceneView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ type Props = {
route: Route & { state?: NavigationState };
getState: () => NavigationState;
setState: (state: NavigationState) => void;
setOptions: (
cb: (options: { [key: string]: object }) => { [key: string]: object }
) => void;
};

export default function SceneView({
Expand All @@ -25,6 +28,7 @@ export default function SceneView({
navigation: helpers,
getState,
setState,
setOptions,
}: Props) {
const { performTransaction } = React.useContext(NavigationStateContext);

Expand All @@ -34,8 +38,16 @@ export default function SceneView({
setParams: (params: object, target?: TargetRoute<string>) => {
helpers.setParams(params, target ? target : { key: route.key });
},
setOptions: (options: object) =>
setOptions(o => ({
...o,
[route.key]: {
...o[route.key],
...options,
},
})),
}),
[helpers, route.key]
[helpers, route.key, setOptions]
);

const getCurrentState = React.useCallback(() => {
Expand Down
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export { default as createNavigator } from './createNavigator';

export { default as useNavigationBuilder } from './useNavigationBuilder';
export { default as useNavigation } from './useNavigation';
export { default as useOptions } from './useOptions';

export * from './types';
8 changes: 8 additions & 0 deletions src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ export type NavigationProp<ParamList extends ParamListBase = ParamListBase> = {
params: ParamList[RouteName],
target: TargetRoute<RouteName>
): void;

/**
* Update the options for the route.
* The options object will be shallow merged with default options object.
*
* @param options Options object for the route.
*/
setOptions<Options extends object = object>(options: Options): void;
} & PrivateValueStore<ParamList>;

export type RouteProp<
Expand Down
3 changes: 3 additions & 0 deletions src/useDescriptors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export default function useDescriptors<ScreenOptions extends object>({
removeActionListener,
onRouteFocus,
}: Options) {
const [options, setOptions] = React.useState<{ [key: string]: object }>({});
const context = React.useMemo(
() => ({
navigation,
Expand Down Expand Up @@ -67,6 +68,7 @@ export default function useDescriptors<ScreenOptions extends object>({
screen={screen}
getState={getState}
setState={setState}
setOptions={setOptions}
/>
</NavigationBuilderContext.Provider>
);
Expand All @@ -79,6 +81,7 @@ export default function useDescriptors<ScreenOptions extends object>({
navigation,
})
: screen.options),
...options[route.key],
},
};
return acc;
Expand Down
9 changes: 9 additions & 0 deletions src/useOptions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import useNavigation from './useNavigation';

export default function useOptions<Options extends object = object>(
options: Options
) {
const navigation = useNavigation();

navigation.setOptions<Options>(options);
}

0 comments on commit 8a09d94

Please sign in to comment.