React - How to connect / disconnect children components to data from parent based on click?

Viewed 380
  • Parent component provides data to child component (that displays it) (have multiple children). The child component has 2 buttons connect and disconnect. When connected to should receive and show the data, when disconnected clicked, it should disconnect from data.

  • How I would do it: child calls method in parent for connect/disconnect,then i would have a flag in parent state and based on that either render child with or without data, then inside child i render props or null if no props provided.

  • That would mean if I have 10 child components, I would need 10 flags which doesnt seem good, so I 2nd idea:

  • having the flag insight the child and method for triggering connect/disconnect, render based on if props were provided

My question is, is there a good practice react way of connecting children to parents data flow/stopping data flow without always passing data to children and just rendering/not rendering it based on if child 'wans' to be conencted or not? Thanks!

1 Answers

Did you try using Redux or Context API? The two are very similar and it should get what you want. They basically use 1 store(think of them multiple states are connected to 1 store) and you get data from child components.

After getting your data you can check if user is logged in or not and put your buttons according to this data.

If I was not clear enough feel free to ask any question.

Also official docs for Redux and Context API are: https://redux.js.org/introduction/getting-started https://tr.reactjs.org/docs/context.html

Related