LoginSignup
1
2

More than 5 years have passed since last update.

react stateを使わずにmobxでreact-beautiful-dndを動かす方法

Last updated at Posted at 2018-02-28

サンプル

問題

https://github.com/atlassian/react-beautiful-dnd
で用意されているサンプルはstateを使っているため、そのままmobxに変更してもうまく機能しない。
問題の場所は(provided, snapshot) => ()関数内でmobx observableオブジェクトthis.itemsを使う必要がある事で、この関数内ではthis.items自体がobservableとしてうまく機能していない。

  @mobx.observable items = [{id: "...", content: "..."}]

  ...
  ...
  ...

  render() {
    return (
      <DragDropContext onDragEnd={this.onDragEnd}>
        <Droppable droppableId="droppable" direction="horizontal">
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              style={getListStyle(snapshot.isDraggingOver)}
              {...provided.droppableProps}
            >
              {
                // ここでobservableが必要になる
              }
              {this.items.map((item, index) => (
                <Draggable key={item.id} draggableId={item.id} index={index}>

解決策

(provided, snapshot) => ()関数内の部分を別コンポーネントとして切り出して、そのコンポーネントを@observerを使いobservableオブジェクトを正しく機能させる。

https://github.com/github0013/react-beautiful-dnd-mobx/blob/master/src/App.tsx#L49
https://github.com/github0013/react-beautiful-dnd-mobx/blob/master/src/DraggableInternal.tsx

1
2
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
1
2