3
\$\begingroup\$

I am doing a filtered table in react, and I came up with the following code:

import React from 'react';
import { render } from 'react-dom';
import RowFilter from './RowFilter';
import List from './List';
import movieList from './movielist.json';

const data = movieList;
const App = () => (
  <RowFilter data={data}>
    <List/>
  </RowFilter>
);

render(<App />, document.getElementById('root'));

The implementation details are not that important since this is only a rough example, but the general idea is the following:

List normally expects a data array property so that it knows what to render

RowFilter has an input element and keeps track of a list of data. When the value changes, it updates the list of data.

RowFilter also sets the data property for it's child, whatever that child is

The result code works as expected, but I'm wondering about whether this is hard to read or considered a bad practice in general.

Running example

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

I agree with what Dan Bovey says, and I would go one step further to make it more explicit and make RowFilter take a render prop:

<RowFilter
  data={data}
  render={(filteredData) => <List data={filteredData}/>}
/>

With this you can see exactly what is getting passed to your List, and you can use this RowFilter to wrap other components too.

\$\endgroup\$
2
2
\$\begingroup\$

Yeah it's hard to read and only by looking at the source for RowFilter can you understand that it's injecting props into the child component that is given to it. Instead of passing it in as a child, you should pass it in a component prop.

<RowFilter data={data} component={List} />

Then in RowFilter.js, the render simply looks like this. Note the component prop gets renamed to uppercase.

<Component data={this.state.filteredData} />

Here's an updated example on codesandbox

\$\endgroup\$

Your Answer

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

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