Search code examples
react-nativecoffeescript

Use react native Text component in filter loop


I'm trying to render a hierarchical component view (in Coffeescript) from an object that contain parent/child relations

My object looks like

this.state =
  data: [
    {
      id: 1
      name: 'Category 1'
      type: 'category'
    },{
      id: 2
      parent: 1
      name: 'Task 1'
      type: 'task'
    },{
      id: 3
      parent: 1
      name: 'Task 2'
      type: 'task'
    },{
      id: 4
      name: 'Category 2'
      type: 'category'
    },{
      id: 5
      parent: 4
      name: 'Task 3'
      type: 'task'
    },{
      id: 6
      parent: 4
      name: 'Task 4'
      type: 'task'
    }
  ]

My current approach is as follows

render: ->
  <Text>Hierarchy</Text>
  { this.state.data.map( ( data ) =>
    if data.type == 'category'
      this.renderView( data )
  ) }

and

renderView: (data) ->
  <View>
    <View>
      <Text>{data.name}</Text>
    </View>
    <View>
      { result = this.state.data.filter( ( obj ) ->
        if obj.parent == data.id
          <Text>{obj.name}</Text>
      ) }
    </View>
  </View>

The code above however results in the following error

Invariant Violation: Objects are not valid as a React child (found: object with keys {id,parent,name,type})

I know that in the filter() loop the correct data is available. Somehow i can't use the React Native <Text> element there, but why?


Solution

  • First of all, return the renderView method from render

    render: ->
      <Text>Hierarchy</Text>
    {
      this.state.data.map((data) =>
        if data.type == 'category'
          return this.renderView(data)
      ) }
    

    also, you have to filter theresult first and map over it

    renderView: (data) ->
      { var result = this.state.data.filter(obj => obj.parent == data.id) }
      <View>
      <View>
        <Text>{data.name}</Text>
      </View>
      <View>
        {result.map(val => val.name)}
      </View>
      </View>
    

    PS: I don't know the syntax of coffescript much, sorry for any typo, but the logic would work fine.