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

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 24, 2018 at 8:59
\$\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.

answered Feb 2, 2018 at 18:02
\$\endgroup\$
2
  • \$\begingroup\$ I really feel I should change my accepted answer now but I don't know what's the proper Stack Etiquette on this... \$\endgroup\$ Commented Feb 7, 2018 at 7:45
  • \$\begingroup\$ I'm not really sure either. meta.stackexchange.com/questions/93969/… \$\endgroup\$ Commented Feb 8, 2018 at 0:27
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

answered Jan 25, 2018 at 13:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.