LoginSignup
8
4

More than 5 years have passed since last update.

Render PropsとHooksでシンプルな状態管理層を作る

Last updated at Posted at 2019-03-06

Storybookとか、デザインシステムのドキュメントを作るときに便利。

コード(TypeScript)

import React, { useState } from 'react'

interface RenderProp {
  (
    object: {
      state: boolean
      setState: (newState: boolean) => void
    }
  ): React.ReactNode
}

interface Props {
  render?: RenderProp
  children?: RenderProp
  initialState: any
}

function StateManager(props: Props) {
  const [state, setState] = useState(props.initialState)

  return <div>{props.children({ state, setState })}</div>
}

export default StateManager

使い方

モーダルの表示非表示を制御するサンプル。

<StateManager initialState={false}>
  {({ state, setState }) => (
    <div>
      <button onClick={() => setState(true)}>
        モーダルを開く
    </button>
      {state && <Modal onClose={() => setState(false)}/>}
    </div>
  )}
</StateManager>
8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4