22
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactの実装パターン (Render Callbacks)

Posted at

あらすじ

React Routerで使う <Route>コンポーネントの使い勝手で、 render propsでサクッと画面を実装するにはどうすればいいんだろう。
あわよくば、状態に応じて表示するものを切り分ける時にサクッと切り分けたいな。

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  <span>Top Page</span>
)}/>

方針

サクッと実装するためにrecomposeの toRenderProps() を使う。

実装

下記の実装はindex.jsで一筆書きです。

import React from "react";
import ReactDOM from "react-dom";
import { toRenderProps, withState, lifecycle, compose } from "recompose";
import { Dimmer, Loader, Segment } from "semantic-ui-react";
import "./styles.css";
import "semantic-ui-css/semantic.min.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const enhance = compose(
  withState("isLoading", "updateLoading", true),
  lifecycle({
    componentDidMount() {
      const { updateLoading } = this.props;
      setTimeout(() => {
        updateLoading(false);
      }, 1000);
    }
  })
);
const Component = toRenderProps(enhance);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Component>
    {({ isLoading }) =>
      isLoading ? (
        <Segment>
          <Dimmer active>
            <Loader />
          </Dimmer>
        </Segment>
      ) : (
        <App />
      )
    }
  </Component>,
  rootElement
);

22
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
22
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?