Pass data between "brothers" components - angularjs

You are probably wondering what I mean by brothers components, well it's simply 2 different components that have the same parent component.
I am using angular.js 5.11
Let's say I have a parent component with a child1 component and a child2 component. I have a variable vm.active in my child1 component and I wish to use it (in an ng-if if you're wondering) in my child2 view.
Any ideas ? Was thinking of doing two way binding in both 3 components ? What do you all think ? Or maybe considering they are from the same state, probably as a stateParams ? Please let me know if you have any questions

This is the perfect scenario to create a service. Remember controllers have unique instances, but a service passes a common instance around.
https://www.w3schools.com/angular/angular_services.asp

Do not use two-way data binding in this case because you can accomplish the same in a more efficient way. Two way binding setup requires framework overhead.
One approach:
Setup one way binding of the variable (say x) in the Parent component to both of the children.
When child1 makes an update to the variable, pass in an observable reference that the parent can receive. The parent can set the value of x accordingly. Now both the children can see the update.
Here's another:
Use a singleton service. Save the variable in a related service. Use the getters and setter methods to retrieve and update the values.

Well ended up using $scope.$parent.$broadcast in first component and $scope.$on on the second component if anyone is wondering :)

Related

How to pass data from grandchild to parent component in React?

I have a form (Parent) which contains an input field (Child), which gets its value from a reference table (Grand-grand-child) that is displayed as a modal (Grand-child) which opens up by clicking a button attached to the input field. This is a nested structure that roughly looks like this:
I need to set the value of the input field by selecting a row in the reference table and confirming my choice with a button "SET VALUE", which means I need to pass data three levels up from Grand-grand-child to Parent through Grand-child and Child.
My state is kept in the Parent component. Is there a simple way of achieving that without using external libraries? Please offer a solution using Hooks as all of my components are functional components.
Here is the code: https://codesandbox.io/s/festive-fast-jckfl
See CreateRate component where:
CreateRate.jsx is the Parent
InputField.jsx is the Child
DataFetchModal.jsx is the Grand-child
Airports.jsx is the Grand-grand-child
Pass a change handler function from parent (where state lives) down to the grand child. The grand child should call this change handler when clicking the Set Value button.
If this is too much prop drilling
look into component composition first
if that doesn’t work out, look into context api
Update:
You mentioned your problem was trying to access the state inside Grand-grand-child from your Grand-child. In this case you can lift the state up (to Grand-child). This means lifting 'airports' up to DataFetchModal. Here is more info on lifting state.
https://reactjs.org/docs/lifting-state-up.html#lifting-state-up
Also, it appears you are running into these problems because your code is very nested and not very composable. I would suggest looking into how you could better break up your components. One way to accomplish this is using compound components.
https://kentcdodds.com/blog/compound-components-with-react-hooks
Determining how to break this up better would take some time. However, just looking at this briefly. You may be able to move your DataFetchModal to your parent. Pass a callback to the InputField to fire it off and send the identifying parameters (what input called it). Then, from the parent, compose in whatever modal body using composition. It appears you have a lookup object (objType) inside DataFetchModal. Maybe this could go away by using composition (not sure, and probably separate topic).
Update 2:
I pulled down your code sandbox and made a few changes that may help access parent level state. I moved the modal into the parent. Check it out.
https://github.com/nathanielhall/Test

When should i assign independent states to child functions(using hooks) in react?

I am making a small project in react which has three child components
a form to input data and later that data is posted to server
Another form to input a key and later fetch its corresponding value from server
Live Display of current data present on server
As of now i have declared all the states required in this project in a function which is a parent of all the functions mentioned above.
I believe i can also declare relevant states separately in child functions independently instead of declaring them in their common parent and the project would work fine .
So ,my question is
what should be the right approach to declare states in above example project ? OR like what is the correct approach in designing architecture for states in general ?
Normally state variable is create in most parent component that needs to read/change the state.
When a child need to read the state, parent passed down it to child as
a prop.
When a child need to write into state, parent pass a callback
function as a prop to child to modify the state.
There is no such thing as 'correct archi'. Just respect the core concept of separation of concerns and you will be forced to build a clean architecture.
For state management, it depend on your needs. I usually love to implement contextApi to handle my stuff but it's just a choice, and it's because i have to share data between multiples components. If you are sure your application won't get fat then handling local state isn't a bad solution, it's easier to implement.
In general and the proper way to declare the states is to define them inside the functional(parent) component. Since you are using hook, you can use React.useState() to define your states.
Eg.
const [state, setState] = React.useState(initialState);
And to change the value of states later, you can simply call the child functions and use the hook function inside to change the value.
setState(newState);

Trigger a function in a child component

There is some related threads, and a lot of opinions on this subject so I will try to summarize my findings. Notice I am a beginner so this is my best bet, and the data I gathered from related posts and this.
In general most people agree that if the parent call's a child it is bad practice. In the related post for this article there is an accepted answer, where the person answers that it is a bad practice but possible. #mat sz answer directed me on the right path. I have updated my sample for others to see. I pass a parameter to my child component. In the child component I add a listener for changes on that parameter:
useEffect(() => {
if (props.toggleClose != null) {
setToggleJobTable(false);
}
}, [props.toggleClose]);
I just toggle that parameter between true/false in my parent. Not beautiful but my best bet on how to do this in react.
Original question
I found a lot of samples in here on how to pass variables to child components, how to raise events from child components to parent components, and even how to pass a function to a child component from parent component. But what about last scenario. How to call a function in a child component from the parent. In this sample I would like to trigger the closeAll function in the child component from the parent:
https://codesandbox.io/s/toggle-all-qxkgy?fontsize=14&hidenavigation=1&theme=dark
I still dont have an answer on this, but a lot of good input in the posts. For me it sounds like the right approach here would be parsing a parameter to the child as parameter. My question is then, if I pass a parameter to the child component. How do I toogle when the parent changes that value, then my closeAll function in the child is called?
It is also stated that it could be wrong design. If you look on my very simple sample how should it else be designed? All input are welcome. I have very little experience with REACT so I am trying to understand how an experienced REACT developer would solve this simple task/sample.
It's not possible, parent components are not able to access the functions inside of child components.
You could use something like Redux or MobX to create a global state and then rely on global state for that, or you, ideally, should restructure your code in a way that does not require this, for example if your function (the one that has to be called inside of parent) changes state of a child component - move that state to the parent component, and then provide that state via props to the child component (along with a setter function, if required).

Avoid components modify parent scope components in Angular JS

Starting with Angular JS,I have read that components cannot access parent scopes, I mean, each component has its isolated scope. I read this is in order a component can modify its own data and not other components data. This helps to avoid situations where some data from a component can be modified from multiple inner components and would be difficult to resolve a problematic situation with data viewing and find which component is the problematic one.
So later, I read that you can pass in some data to a component with "bindings" from parent components, so the inner component cannot access the parent scope but gets information from the parent scope.So untill here, its ok
But I got surprised when I read that with "binding" in components, you can pass in a "property" by reference, so if in the inner component I modify this property, is not I can access the parent scope, but I am modifying the parent scope, right? So, the problematic situations can happen again, right?
Thanks
While accessing $parent in isolated scope is clearly an antipattern, this doesn't mean that modifying objects through bindings cannot cause problems.
It depends if parent component should be aware of changes that are made in this object. If it should, then the problem arises, because deep change detection (e.g. with $scope.watch(..., true)) is costly. In order to avoid this, child component can notify the parent of changes (scope events, & bindings), or use = binding with immutable object (the object is never mutated; any change should result in object being copied to a new one).

Reactjs Another to pass data from child component to it grandparent(s) component without passing callback?

How to do this easily ? I uses Angular so I don't usually think about this problem as Angular does it automatically. in Angular, I can pass a variable from controller down to any "children" directive in any depth, and when that variable is changed, it permeates in all directives and controller who use it.
In React however, one must use callback which is then passed through layers of React component: passing data from child to parent component - react - via callback function.
I use the above solution to pass a single variable through 3 different React components :
APP --> TABLE --> ROW_TABLE
EDIT: It is not that I don't understand how to pass the variable through layers of component. I just think there must be more easier way to do this.
I think this solution is quite complicated. Keep in mind that we usually deal with more than three "components" in the real life. Can someone give me suggestion of how to do this 'right' ?
I'm just learn React for a day now so I must miss something. Thank you
If you want to pass a variable through many childs, the most correct way of doing it in React is just passing them through props.
If you don't want to use this aproach you could use state management libraries like redux.
If you want instead to do this using pure React you could use the component's context, although it is not recommended.
See more about context here https://reactjs.org/docs/context.html

Resources