Suppose I have a component and two contexts. The both contexts can use this component. When context1 uses it, the component should do const context=useContext(Context1)
in itself. When context2 uses it, the component should do const context=useContext(Context2)
in itself. But how can this component know which context is using it now and do the instuction?
3
Answers
You can try making storing some key value in the local storage and get the value in the component from there .
like in context1 just add one line
and in context2 be
now then your component loads just retrive the value from the clocalstorage by
then you will have the currently used context name stored in current named variable..
i tried to answer based on how much i came to get your problem if you face any other issue do comment…
If you’ve got a component that has to choose which context to use I think you should rethink your design. It would be much easier to help if you would explain what the two contexts are and what the component is doing with them, but you don’t seem willing to elaborate.
Is there a reason you can’t have a single context whose value changes, instead of entirely separate contexts? I guess I’ll never know.
If you insist on having two contexts and making your component choose between them you could have a context that specifies which context to use.
You could also just pass it in as a prop:
While I agree that the need to do this is probably a missunderstand of React design, should be not needed; and while ray answer seems more "React way" and elegant… I will give another option.
You could add some flag or info in the default Context values that define if the Context is actually available: