UNPKG

1.8 kBPlain TextView Raw
1import { useObserver } from "./useObserver"
2
3// TODO: this type could be improved in the next major release:
4// type IObserverProps = { children: () => React.ReactNode, render?: never } | { children?: never, render: () => React.ReactNode }
5interface IObserverProps {
6 children?(): React.ReactElement | null
7 render?(): React.ReactElement | null
8}
9
10function ObserverComponent({ children, render }: IObserverProps) {
11 if (children && render) {
12 console.error(
13 "MobX Observer: Do not use children and render in the same time in `Observer`"
14 )
15 }
16 const component = children || render
17 if (typeof component !== "function") {
18 return null
19 }
20 return useObserver(component)
21}
22if ("production" !== process.env.NODE_ENV) {
23 ObserverComponent.propTypes = {
24 children: ObserverPropsCheck,
25 render: ObserverPropsCheck
26 }
27}
28ObserverComponent.displayName = "Observer"
29
30export { ObserverComponent as Observer }
31
32function ObserverPropsCheck(
33 props: { [k: string]: any },
34 key: string,
35 componentName: string,
36 location: any,
37 propFullName: string
38) {
39 const extraKey = key === "children" ? "render" : "children"
40 const hasProp = typeof props[key] === "function"
41 const hasExtraProp = typeof props[extraKey] === "function"
42 if (hasProp && hasExtraProp) {
43 return new Error(
44 "MobX Observer: Do not use children and render in the same time in`" + componentName
45 )
46 }
47
48 if (hasProp || hasExtraProp) {
49 return null
50 }
51 return new Error(
52 "Invalid prop `" +
53 propFullName +
54 "` of type `" +
55 typeof props[key] +
56 "` supplied to" +
57 " `" +
58 componentName +
59 "`, expected `function`."
60 )
61}