Skip to content
Advertisement

how to send data From one component to another components with context in react?

I need to send selectedCoin state from Company to details.js How do I do this with context?

company component:

JavaScript

details components:

JavaScript

Advertisement

Answer

Well, looks like you’re just interested on the code right, so I’ll just drop the code in here. Obviously, feels free to move code around and make sure you use the syntax that does make sense to you

This is the context

CoinsContext.js

JavaScript

To use it, you need to wrap up all the pages that are gonna use the context with it, for example, since you want Details.js and Company.js to use it, you will need to wrap both pages with it. I’ll just wrap the entire App, which means the entire app can use it, but feel free to do what you want.

Would be something like this:

index.js

JavaScript

Now we have the CoinsContext set up, we can use it on your components

Company.js

JavaScript

Details.js

JavaScript

And we’re done! Now you are not just sharing selectedCoin between your components, but you’re also putting all coins fetching logic in your context, which overall is the right thing to do

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement