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 method to set screen options
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.
  • Loading branch information
satya164 committed Jul 22, 2019
1 parent 62f4047 commit 0519693
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 33 deletions.
24 changes: 24 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 method to configure screen options:

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

navigation.setOptions({
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
2 changes: 1 addition & 1 deletion example/StackNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export type StackNavigationOptions = {

export type StackNavigationProp<
ParamList extends ParamListBase
> = NavigationProp<ParamList> & {
> = NavigationProp<ParamList, StackNavigationOptions> & {
/**
* Push a new screen onto the stack.
*
Expand Down
7 changes: 6 additions & 1 deletion example/TabNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,15 @@ export type TabNavigationOptions = {
* Title text for the screen.
*/
title?: string;
/**
* Stuff
*/
label: number;
};

export type TabNavigationProp<ParamList extends ParamListBase> = NavigationProp<
ParamList
ParamList,
TabNavigationOptions
> & {
/**
* Jump to an existing tab.
Expand Down
42 changes: 28 additions & 14 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,20 +65,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);
}, []);

navigation.setOptions({
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
6 changes: 3 additions & 3 deletions src/createNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import { ParamListBase, RouteConfig, TypedNavigator } from './types';
import Screen from './Screen';

export default function createNavigator<
Options extends object,
ScreenOptions extends object,
N extends React.ComponentType<any>
>(RawNavigator: N) {
return function Navigator<ParamList extends ParamListBase>(): TypedNavigator<
ParamList,
Options,
ScreenOptions,
typeof RawNavigator
> {
return {
Navigator: RawNavigator,
Screen: Screen as React.ComponentType<
RouteConfig<ParamList, keyof ParamList, Options>
RouteConfig<ParamList, keyof ParamList, ScreenOptions>
>,
};
};
Expand Down
41 changes: 28 additions & 13 deletions src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@ class PrivateValueStore<T> {
private __private_value_type?: T;
}

export type NavigationProp<ParamList extends ParamListBase = ParamListBase> = {
export type NavigationProp<
ParamList extends ParamListBase = ParamListBase,
ScreenOptions extends object = object
> = {
/**
* Dispatch an action or an update function to the router.
* The update function will receive the current state,
Expand Down Expand Up @@ -208,6 +211,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: Partial<ScreenOptions>): void;
} & PrivateValueStore<ParamList>;

export type RouteProp<
Expand All @@ -224,15 +235,17 @@ export type RouteProp<
});

export type CompositeNavigationProp<
A extends NavigationProp<ParamListBase>,
B extends NavigationProp<ParamListBase>
> = Omit<A & B, keyof NavigationProp<any>> &
A extends NavigationProp<ParamListBase, object>,
B extends NavigationProp<ParamListBase, object>
> = Omit<A & B, keyof NavigationProp<any, any>> &
NavigationProp<
(A extends NavigationProp<infer T> ? T : never) &
(B extends NavigationProp<infer U> ? U : never)
(A extends NavigationProp<infer T, any> ? T : never) &
(B extends NavigationProp<infer U, any> ? U : never),
(A extends NavigationProp<any, infer O> ? O : never) &
(B extends NavigationProp<any, infer P> ? P : never)
>;

export type Descriptor<Options extends object> = {
export type Descriptor<ScreenOptions extends object> = {
/**
* Render the component associated with this route.
*/
Expand All @@ -241,13 +254,13 @@ export type Descriptor<Options extends object> = {
/**
* Options for the route.
*/
options: Options;
options: ScreenOptions;
};

export type RouteConfig<
ParamList extends ParamListBase = ParamListBase,
RouteName extends keyof ParamList = string,
Options extends object = object
ScreenOptions extends object = object
> = {
/**
* Route name of this screen.
Expand All @@ -258,11 +271,11 @@ export type RouteConfig<
* Navigator options for this screen.
*/
options?:
| Options
| ScreenOptions
| ((props: {
route: RouteProp<ParamList, RouteName>;
navigation: NavigationProp<ParamList>;
}) => Options);
}) => ScreenOptions);

/**
* Initial params object for the route.
Expand All @@ -284,7 +297,7 @@ export type RouteConfig<

export type TypedNavigator<
ParamList extends ParamListBase,
Options extends object,
ScreenOptions extends object,
Navigator extends React.ComponentType<any>
> = {
Navigator: React.ComponentType<
Expand All @@ -295,5 +308,7 @@ export type TypedNavigator<
initialRouteName?: keyof ParamList;
}
>;
Screen: React.ComponentType<RouteConfig<ParamList, keyof ParamList, Options>>;
Screen: React.ComponentType<
RouteConfig<ParamList, keyof ParamList, ScreenOptions>
>;
};
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

0 comments on commit 0519693

Please sign in to comment.