DEV Community

Takaya Kobayashi
Takaya Kobayashi

Posted on

3

recompose で ref を扱う

recompose を使うと見た目の component とロジックを切り離して書けるのでスッキリする、というような記事を先日書いた(Storybook Driven Development を試している)のだが、React の ref の使い方で大いにハマったので書いておく。

アプリケーションを作っていると、往々にして componentDidUpdate などで ref を参照したいということが発生する。普通に class で書いていると

class extends React.Component {
  componentDidUpdate() {
    this.textarea // => <textarea />
  }

  render() {
    return (
      <textarea ref={textarea => (this.textarea = textarea)} />
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

という風に書くが、recompose を使っていると

const enhance = lifecycle({
  componentDidUpdate() {
    // ???
  }
})

enhance(() => (<textarea ref={???} />))
Enter fullscreen mode Exit fullscreen mode

というような形に分離する。この時、先に示したように refthis に代入しても、componentDidUpdate の中では thisProxyComponent となっていて ref が読み出せなくなってしまう。これを解決するためには、withHandlers を併用する。

const enhance = compose(
  withHandlers(() => {
    let refs = {}
    return {
      onRef: props => textarea => (refs.textarea = textarea),
      onUpdate: props => refs.textarea // として参照できる!!
    }
  }),
  lifecycle({
    componentDidUpdate() {
      this.props.onUpdate()
    }
  })
)

enhance(props => (<textarea ref={props.onRef} />))
Enter fullscreen mode Exit fullscreen mode

これで recompose でも ref を取り扱うことができた。

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay