r/reactjs • • Jun 23 '19
Needs Help How to reuse components that display different data from the api?
[deleted] — view deleted post
3
Upvotes
r/reactjs • • Jun 23 '19
[deleted] — view deleted post
2
u/[deleted] Jun 23 '19
A nice method of building out an extensible data table component would be to use the Compound Component pattern. This will help avoid complex props as your data table becomes more complex over time.
Kent C. Dodds has a nice run down on the pattern here:
https://kentcdodds.com/blog/compound-components-with-react-hooks
It's not prescriptive so you'd need to think about what best fits your situation.
1
u/TotesMessenger Jun 23 '19
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
1
u/do_moura19 Jun 23 '19 edited Jun 23 '19
You should pass the array returned from the api and render it on the component in a generic way, I do it this way
The component will receives a "propsToRender" which contains the props name that it will render inside it example:
Inside the component you should iterate on the data and render all the properties that matches with propsToRender, but first you render the "propsToRender" as the header...if you want a different header name than the property name you can pass an array of object instead an array of strings like this:
do it in a generic way that you can also render the table without specifying the propsToRender(only use it when you wants to specify which props to show or show the header with a different name than the property name), instead of using the propsToRender you will iterate though the properties of your first index of data and save every property name into a separate string array(just like the first propsToRender example) to use it as a Header name.