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" />
  }
];
Sign up to request clarification or add additional context in comments.

2 Comments

Creator and maintainer of React-Table here... This is the correct answer.
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..
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 Comment

I like this answer...just a slight edit, add a closing curly bracket in ({ cell: { value }) to become ({ cell: { value }})

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.