Search code examples
javascriptreactjsreact-bootstrap

Displaying firstname and last name in the same column in react-table-2


I have an API rendering some user data, first- and last name etc.:

users = [{
  firstname: 'Peter',
  lastname: 'Pan'
  address: 'someAddress'
},
  firstname: 'Winnie',
  lastname: 'thePoo'
  address: 'someOtherAddress'
}]

Now, I would like to display the name in the same column in the react-table-2 to enable searching for both first- and last name. What is the best way to do this? I have tried formatting the data through the "formatter" property, but it does not seem to work well when searching.

Any ideas? I would like to avoid changing the API


Solution

  • import React, { Component } from 'react';
    
    const data = [
      {
        firstname: 'Peter',
        lastname: 'Pan',
        address: 'someAddress'
      },
      {
        firstname: 'Winnie',
        lastname: 'thePoo',
        address: 'someOtherAddress'
      }
    ]
    
    class TwoFielSameColumn extends Component{
    
        render(){
          const finalData = data.map(item => ({
            ...item,
            fullName: `${item.firstname} ${item.lastname}` || "",
          }))
        
          return(
            <div>
              {finalData.map((q) => <div>{q.fullName}</div>)}
            </div>
          )
        }
    }
    
    export default TwoFielSameColumn;
    

    Use finalData of tabledata