Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

あらすじ

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
);

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした