Use states and functions of a component in another component - javascript

I have two separate component and they do not have parent child relation (I cannot render component B in component A) so I cannot write and pass props to it. Is there a separate way to use component A's states and functions in component B?
I am a bit confused since I am a beginner.

from what I understand they have both the same father so
look at Context API that way you wrap the father and then both of them will have the same state and function you pass.
context API official doc

I had the same problem and used the use-global-hook npm package.
Here is an article with an example on how to use it:
And here is a section from the article that may be of interest:
This is just a personal preference, but I try to avoid context API if possible. Here is an article outlining its pitfalls

Related

What is a good practice to access the parent component's ref inside its child?

I'm coding a small library with a simple structure: one parent component can contain multiple components of the same type as direct children. Here is a sample schematic diagram for the app:
By current design, a ChildComponent must address a variety of properties of their parent MainComponent, and I am looking for a good practice that can help achieve that or an alternative of an app structure that will lead to a good practice.
My considerations:
Using Context API. This won't go well with the goal in mind because of the nature of contexts. As per linked documentation:
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Passing all required props from MainComponent to ChildComponent. Despite I meet this approach quite often, I don't think it is good because it leads to duplicate code.
The simplest way is with Props, as you already mentioned. If you are passing only one level down it is probably the best option:
https://reactjs.org/docs/components-and-props.html
If you need to pass code to several children and grandchildren, using props will get annoying, that is called "propdrilling". You can avoid it using a Context that will provide to all the components that want to consume it:
https://reactjs.org/docs/context.html
Another alternative for larger applications is Redux. Is has a store and enables your components to interact with the Redux store. The downside is that it requires a lot of boilerplate.
https://react-redux.js.org/

Can I get click methods inside vuex

I just started learning Vue and Vuex. I saw that I have the same code in different components. I started using Vuex and i store my data inside index.js and it's really helpful.
My questions is, how can I store click functions with vuex. In the code below is simple example
<button #click="clickMe">Click Me</button>
methods: {
clickMe() {
console.log('Hellouu')
},
}
Keeping the logic of a component in itself is what component-based approach is about. A click listener on a component or its sub-element is very personal and private to a component.
Mixins
But.. let's say you have a situation where you have the same exact logic that needs to be executed on-click on multiple components, the answer will be to use mixins. Store is not the place to do it. This holds and is true for any case where you need to 'share reusable functionalities'.
Apart from providing flexibility, mixins have a number of benefits, for instance, you can take advantage of the option merging rules within mixins to override the onClick() method described in a mixin to cater for a special case within one of the components, but continue to use the rest of the common logic the mixin contains.
Note: Be careful though, Hook functions with the same name are instead merged into an array so that all of them will be called. Mixin hooks will be called before the component’s own hooks.
Read more (optional)
As a great real world example check out this repository: https://github.com/buefy/buefy. Its a UI components library that is built with Vuejs. You can find many more examples and best practices in such open source repositories and these are always a great reference point for writing better code.

Does the React Context API replace the need for component props?

I've recently upgraded a React 15 project to use React 16.9. Specifically, I've completely replaced redux with the new Context API, pure functional components, and hooks. With the Context API, we also gain the ability for nested child consumers to obtain the data without having to pass it using props all the way through. However, I noticed that I don't have any component props anywhere as everything is passed via provider/consumer context.
So my question is does the context API make component props obselete?
I find people abuse redux and context. Btw, redux uses context internally.
To be honest, prop still should be your best friend in most of cases. Only when you want to avoid nested prop passing, you could then explore context where a provider is created as a parent, and then all deep down children can receive it as props.
Prop is still the way when children connect to the provider. The only difference is that these props are stored in a sort of "global" space now.
So in short, context doesn't replace prop, it still uses prop.
You have already answered your question. Context API avoids I quote one from react docs :
Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult
There is no other reason. If I want to reuse component or export it that depends context, user has no idea about it. Use cases like logged User, theme, or sone global state like work flow detail for the whole application etc, makes a good use case.

Global state in a (wix) react-native-navigation app?

I'm putting together an app with react-native-navigation.
I need to have some global state available but I can't figure out how to implement it. Usually I'd have a stateful top-level component and pass methods that call this.setState to lower components as props—but the two Navigation methods provided by react-native-navigation, startTabBasedApp and startSingleScreenApp, cause any parent component to dismount. Dismounted components can't have state changed according to the error logs, so I'm at a loss.
What am I missing? How can I share state between my components (screens) with this solution?
Consider using Redux. There is an example here- https://github.com/wix/react-native-navigation/tree/v1.1.81/old-example-redux
It is unmaintained but the principle should be the same. My app works fine with it even on version 1.1.81.

EmberJS - Calling components methods from outside with a couple solutions (call for discussion)

The following is from an issue I posted on EmberJS GitHub, but Stack Overflow is better suited for a discussion than GitHub.
I am building a few complex components at the moment including composite components and I hit a roadblock with the extreme isolation components live in.
There are several cases where I don't need the components to trigger an action on a controller, but where a controller needs to trigger a behaviour change on the component.
Problems is that the components don't know about the controller and the controller is not creating the components either: they are defined in a template.
I kind of solved the problem by subclassing the Ember.Component class to offer a way for messages to get through components.
The new component subclass breaks the on purpose isolation of components that shouldn't know about the outer controller.
The 2 less invasive options I found to make component methods calls from outside are:
Cache component / name of instance pairs in a global array like
App.components, then call a component method with
App.components['name'].method()
Trigger events from outside, register and handle them in the
components. However in that case I am passing an eventSource object
to the component, often a controller like so: {{my-component
eventSource=controller}}
My question is about how could we solve this problem in the most elegant and less invasive way possible for components ?
For achieving composite components, using the components like lego pieces, it seems impossible to me at the moment to see how we can achieve that goal without breaking the components isolation.
Any input, ideas, solutions, discussion is very welcome.
Note: By the way, the first method that breaks the component isolation is inspired by the work done on the ember-bootstrap components: https://github.com/ember-addons/bootstrap-for-ember
The author had to solve the same problem of being capable of triggering methods inside the components from outside.
Another note: Just for the record, another way to access a component is to use Ember.View.views['name'] where name is a view name you gave to your component. However I feel dirty to make such calls, even more from a controller.
In general, I would try to solve this by binding properties to your component, which could then change according to computed properties or observers based on those properties.
For instance, instead of trying to call a method like deactivate on a component, bind a property such as active to a property in the template:
{{my-component active=formEnabled}}
I'm hesitant to recommend passing an eventSource to components as a general solution (like your {{my-component eventSource=controller}} example). I imagine this could work with a class or mixin that just emits specific events and is tightly coupled with your component, but I'm struggling to come up with a use case that justifies this approach.

Categories