Skip to content

Instantly share code, notes, and snippets.

@vbfox
Last active October 24, 2018 12:42
Show Gist options
  • Save vbfox/c58d6ef9db4ea72153e256fe965534d0 to your computer and use it in GitHub Desktop.
Save vbfox/c58d6ef9db4ea72153e256fe965534d0 to your computer and use it in GitHub Desktop.
React 16.6 Fable 1
module MemoReactHelpers
/// A special ReactElement that tell React to not render anything
[<Emit("null")>]
let noElement = jsNative<ReactElement>
[<Erase>]
type ComponentClass<'props, 'state> = class end
[<RequireQualifiedAccess>]
module ComponentClass =
/// The displayName string is used in debugging messages. Usually, you don’t
/// need to set it explicitly because it’s inferred from the name of the
/// function or class that defines the component. You might want to set it
/// explicitly if you want to display a different name for debugging purposes
/// or when you create a higher-order component
let inline setDisplayName (comp: ComponentClass<_, _>) (name: string) =
comp?displayName <- name
let inline func<'props> (f: 'props -> ReactElement): ComponentClass<'props, obj> =
unbox f
let inline namedFunc<'props> (name: string) (f: 'props -> ReactElement): ComponentClass<'props, obj> =
let result = func f
setDisplayName result name
result
/// If your function component renders the same result given the same props,
/// you can wrap it in a call to React.memo for a performance boost in some
/// cases by memoizing the result. This means that React will skip rendering
/// the component, and reuse the last rendered result.
[<Import("memo", from="react")>]
let memo<'props> (f: 'props -> ReactElement): ComponentClass<'props, obj> =
jsNative
let inline namedMemo<'props> (name: string) (f: 'props -> ReactElement): ComponentClass<'props, obj> =
let result = memo f
setDisplayName result name
result
/// Create a ReactElement to be rendered from a ComponentClass, props and children
let inline createElement<'props> (comp: ComponentClass<'props, _>) (props: 'props) (children: ReactElement seq): ReactElement =
createElement(comp, props, children)
module Test
type [<Pojo>] Props = { Name: string }
let private showNameComponent = ComponentClass.namedMemo "ShowName" (fun props ->
span [] [str props]
)
let inline showName name =
ComponentClass.createElement showNameComponent { Name = name } []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment