mardi 14 avril 2020

Extracting actions from child component to parent

I've been trying to build a react based application, and I am stumped with how to solve this situation:

Let's say I have a component called "SimpleTable" that provides as the name says, a simple table - the props for it are "headers" (array), "rows" (array) and "paginated" (bool)

If the paginated is false, then we just give a simple long table - if it is true, we chunk the rows to multiple small tables, and provide buttons to toggle prev/next - so far so simple.

Now comes the challenge part - I want to sometimes have the table as just a table in my code, and sometimes I want to wrap it in a "card" element. I have introduced a new prop to the component called "asCard" (bool), which changes the output of the html, and changes where the prev/next buttons are placed.

Is there a way to reverse this, so that instead of having "asCard" in my component, I would have a wrapper component that I can put anything in, and it can "extract" actions from the child component, and place them in a different position - this way I could have many different components, and would not have to worry about having "asCard" on each of them.

What I am thinking is maybe having a "Card" component, and have a function in it called something like "extractAction", and then it passes it to the child component, and the child component then has a check for a prop called "handleExtractAction" which then passes the action element to, instead of using it in it's own output. But I am not sure if this is a overly complicated way of doing this, and if there is a more sensible way of doing it.

Aucun commentaire:

Enregistrer un commentaire