Aessandro
Aessandro

Reputation: 5761

Mobx observable map to js array

I have a component which gets passed as a prop the value of "form.$('userProfile').fields" which is an observable map like shown in the console.log screenshot:

class Location extends React.Component<*> {
    render() {
        console.log(this.props.fields);
        this.props.fields.map(function(i, el){
            console.log(i, el)
        })
        return (<h1>location fields</h1>);
    }
}

enter image description here

Is it possible to do something like this:

this.props.fields.map(function(i, el){
    console.log(i, el)
    // render React components
})

where you can render subcomponents based on the values you get back from inside the map method?

Upvotes: 2

Views: 3488

Answers (1)

Tholle
Tholle

Reputation: 112777

You can use values or entries on the observable Map to get an iterator of all values or entries, and spread it in a new array and map over that:

class Location extends React.Component<*> {
  render() {
    return (
      <div>
        <h1>location fields</h1>
        {[...this.props.fields.entries()].map(function(entry) {
          return (
            <div key={entry[0]}>
              {entry[0]}: {entry[1]}
            </div>
          );
        })}
      </div>
    );
  }
}

Upvotes: 4

Related Questions