15

I'm attempting to add a component inside the data using react-table package (https://www.npmjs.com/package/react-table#example)

Using the example from the package readme, I'm trying to use a fancy component to add an image to a cell: using ** to jump out in the code... I have also tried:

imageUrl:{<PlaceholderImage width={60} textColor="#fff" text="Image"/>}

example:

import ReactTable from 'react-table'
import 'react-table/react-table.css'
**import { PlaceholderImage } from 'react-placeholder-image'**

render() {
  const data = [{
    name: 'Tanner Linsley',
    age: 26,
**imageUrl:<PlaceholderImage width={60} textColor="#fff" text="Image"/>,**
    friend: {
      name: 'Jason Maurer',
      age: 23,
    }
  },{
    ...
  }]

  const columns = [{
    Header: 'Name',
    accessor: 'name' // String-based value accessors!
  }, {
    Header: 'Age',
    accessor: 'age',
    Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
  }, {
    Header: ' ',
    accessor: 'imageUrl', // String-based value accessors!
    maxWidth: 70,
    minWidth:70,
  },{
    id: 'friendName', // Required because our accessor is not a string
    Header: 'Friend Name',
    accessor: d => d.friend.name // Custom value accessors!
  }, {
    Header: props => <span>Friend Age</span>, // Custom header components!
    accessor: 'friend.age'
  }]

  return <ReactTable
    data={data}
    columns={columns}
  />
}

2 Answers 2

41

You're passing a react component to a data field that expects a string. Try customising your cell via Cell props:

const columns = [
  {
    Header: "Image",
    accessor: "imageUrl",
    maxWidth: 70,
    minWidth: 70,
    Cell: props => <PlaceholderImage width={60} textColor="#fff" text="Image" />
  }
];
2
  • 32
    Creator and maintainer of React-Table here... This is the correct answer. Sep 11, 2019 at 14:10
  • What if we want to generate this on the backend? Anywhere we want to define columns we have to do it in JSX. If we can get access to properties cell.column.attribute we can render it our own way, but it seems that goes against the way this library is supposed to be used..
    – Nickvda
    Aug 20, 2020 at 16:33
24

In addition to @Clarity's answer, there's also a possibility to access the cell's value at the Cell's property level:

const columns = [
  {
    Header: "Image",
    accessor: "imageUrl",
    maxWidth: 70,
    minWidth: 70,
    Cell: ({ cell: { value } }) => (
      <img
        src={value}
        width={60}
      />
    )
  }
];
1
  • 2
    I like this answer...just a slight edit, add a closing curly bracket in ({ cell: { value }) to become ({ cell: { value }})
    – Edrich
    Sep 14, 2020 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.