UNPKG

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