0

I'm using Redux, Immutable.JS, and React. I want to pass an Immutable.JS list into my stateless React component. This component maps through the list and renders a child per item in the list.

Example:

function Cats(props) {

  function Cat(p) {
    return <li key={p.id}>p.name</li>;
  }

  return <ul>{props.cats.map(Cat)</ul>;
}

The {p.id} part breaks, because props.cats is an Immutable.JS list of maps, so I'd have to update my React component to say {p.get('id')} instead.

I'd be okay to do this, but are there better ways for a stateless React component to consume a list without having to know that it's an Immutable.JS list? This usage violates the best practice in the Redux + Immutable.JS + React best practice, "Use Immutable.JS everywhere except your dumb components". 1

I'm certain other people have dealt with this problem and I don't want to reinvent the wheel.

Dillon
  • 493
  • 4
  • 11

2 Answers2

0

You are not wrong. If using ImmutableJs what you should do is p.get('id') the other way would be something like props.cats.map(elem => <Cat id={elem.get('id')} key={elem.get('id')}/>) or IMHOP less elegant props.cats.map(elem=>elem.toJs()).map(Cat) but its just different ways of doing the same thing.

Hope it helps

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30
0

Can relate with your pain, I have documented this here - What are disadvantages to using immutable state in React?.

For Redux

You can use mapStateToProps to convert immutables into normal JS (state.toJSON()). So the dumb (don't like that term) components should be abstracted from the actual structure of your state.

Otherwise

This is an issue anywhere you want abstraction between your state library and your views. One way I have been able to isolate this to some extent is to use (lenses)[https://medium.com/@drboolean/lenses-with-immutable-js-9bda85674780]. If they seem too complicated, you can make a get([key path], source) method and send that in props to your components and use it to fetch the value. This at least provides some abstraction.

hazardous
  • 10,627
  • 2
  • 40
  • 52