0

According to React's documentation:

A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props.

Let's take for example a DropdownList and break it into smaller pieces: DropdownList

Applying React's ideology on the DropdownList would imply that the DropdownList component manages the state for both the Popup and the List by responding also to UI events. A very good implementation in this way can be found here http://jquense.github.io/react-widgets/docs/#/dropdown-list (see the GitHub code).

Another approach could be for each component to manage its own state, where possible. I tried to write a minimalist version of my own DropdownList (please mind the CSS..) that uses a stateful List. A short example on how the List manages its state:

_onMouseDown: function (index, event) {

    if(!this.state.data[index].disabled) {
        this.setState({
            selectedIndex: index,
            focusedIndex: index
        });

        this.props.onSelectedIndexChange(event, index);
    } else {
        event.preventDefault();
    }
}

Here's the full jsfiddle: http://jsfiddle.net/5d30pctd/

I won't compare these two approaches, since both have weak and strong points, but rather ask you how it would be easier for consumers to re-use: a stateful or a stateless List?

tbodt
  • 16,609
  • 6
  • 58
  • 83

1 Answers1

0

For highly reusable components, I recommend a hybrid approach. If the user of the component passes value and onChange, it becomes a controlled component and the value is solely controlled by the value property. If there is no value property, the component stores its own state. This is how the built-in form components like <input> work. This StackOverflow answer contains a more in-depth discussion on the subject.

Community
  • 1
  • 1
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • Thanks for the answer. I'm asking this more in the direction of having a stateful base List that is filterable / sortable / custom rendering / accesible / groupable / multiple selection / scrollable. This would pretty much help to build other components as well, like a Menu or a Double List Selection. If the List is stateful, then the Menu or Double List Selection will be easier to be implemented as the List control its own state and you don't have to write code for it in the parent components. –  Apr 23 '15 at 10:15
  • @cosmi.nu Gotcha. I think my recommendation still stands in that case; if List is only stateful, it becomes very hard for Menu or DoubleListSelection to be controlled components. If it handles both controlled and uncontrolled, Menu and DoubleListSelection can also handle both. – Michelle Tilley Apr 23 '15 at 15:41