3

So I'm using a vanilla React UI component library and MobX as state management in my app. When I have an observable of array as data and I want to pass it down from my component (which is a mobx-react observer) to the UI library's component (which the prop is the type of PropTypes.array), the component rejects it saying my observable array is an object, not an array.

// my store
class Store {
  @observable data = [...];
}


// my component
@inject('store')
@observer
class MyComponent extends React.Component {
  ...
  render() {
    const {store} = this.props;
    return <LibComponent data={store.data} />
  }
}

// library's component
class LibComponent extends React.Component {
  static propTypes = {
    data: PropTypes.array,
    ....
  }
}

I've read about using toJS from mobx in this similar question, but is there any other way to work around this? As I'm not the owner of the UI library I can't add PropTypes validations which come in mobx-react package mentioned in that question as answer. Will the UI library react to change with toJS as input of its prop?

panjiesw
  • 156
  • 1
  • 12

2 Answers2

3

mobx-react ships with it's own propTypes, which you can use: https://github.com/mobxjs/mobx-react#proptypes

mweststrate
  • 4,890
  • 1
  • 16
  • 26
  • Thx @mweststrate, I do know that `mobx-react` have its own propTypes but it's for the component library. Meanwhile I'm trying to use such library which doesn't use `mobx-react` propTypes to validate its prop, but a standar `prop-types` of array type. Is there any workaraound? – panjiesw May 22 '17 at 19:12
  • Library components should probably not be receiving observables in the first place (unless they are observers themselves). Just convert to plain data in the closest surround observer component – mweststrate May 23 '17 at 19:57
1

It is because a mobx array is actually an object.

Documents state that whenever a situation like yours occurs data should be passed as;

data.slice()

In order to turn it into a normal array. Since the library in question most likely lacks the observer decorators as well, I think even if you were to pass the observable down with its reactive qualities, it wouldn't work. Therefore you should either handle this as a nonreactive data, or fork the library to accommodate this need.

Tukan
  • 2,253
  • 15
  • 17