Can I rearrange passed data in a presentational component

Viewed 52

Your answers have highlighted an oversight on my part. I was taking this pattern container/presentational way too seriously and this made me realize that we could do without <Component />.


Say I have two components, <ComponentContainer /> and <Component /> and the latter renders a <Table /> component. For the sake of an example, I use Table from Ant Design.

Now, <Table /> is expecting a property dataSource with the following shape:

const dataSource = [
  {
    key: '1',
    name: 'Mike',
    age: 32,
    address: '10 Downing Street',
  },
  {
    key: '2',
    name: 'John',
    age: 42,
    address: '10 Downing Street',
  },
];

Where should I initialize this variable? Do I have to set it in ComponentContainer and pass it down to <Component /> which just passes it further down to <Table> I initially passed down some unformatted data to <Component />, say (note: the shape might also be something completely different):

const data = {
  {
    name: 'Mike',
    age: 32,
    address: '10 Downing Street',
  },
  {
    name: 'John',
    age: 42,
    address: '10 Downing Street',
  }
}

and then declared and set that dataSource variable in <Component /> using this data:

const { data = [] } = props
const dataSource = data.map((pieceOfData, i) = > ({
  ...pieceOfData,
  key: i
}))

<ComponentContainer > is not supposed to know that <Component /> is using a <Table /> so for me, it was ok to pass down some unformatted data to shape it then as needed further down the component tree even though we are in a presentational component. But I was told otherwise so I don't know. Is it really bad to do anything else than rendering?

2 Answers

This is known as prop-drilling, a process you go through to pass your data down in the React component tree. While it's not a bad pattern, there are some issues when trying to use it from such top-level components. Usually we want to keep logical pieces together and a clear distinction between presentational and logical components.

If you want to read more about it, I highly suggest Kent C. Dodds text on prop-drilling. The text has the potential issues and how to go around it, like using state management or React's Context API.

I recommend reading the beginning of this article by Dan Abramov https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

It used to be that everyone lived and died by the presentational and container component idea and prop drilling. I tend to disagree with that model. I believe that the component logic and information should live as close as possible to where it's being used. It makes it easier for me to read and understand what code is doing if I don't have to constantly check back up 2 files to see what is being passed down. As stated in the other answer by Inacio there are good ways around this issue especially with the use of hooks.

Related