Skip to content
Advertisement

Creating Plugins in React

I am learning React. I have experience with Vue.js. Vue.js has the concept of plugins which allow you to inject functionality across pieces of your app. The pieces may be components, state management, router, etc. A common need for plugins is translation or logging. My question is, does React have a concept like plugins or services? If so, what is it?

I do not see anything similar to plugins in the React docs. Several blog posts I’ve reviewed, do not seem to use plugin in the same way. How can one provide programmatically accessible functionality that is available globally throughout a React app?

Advertisement

Answer

A common pattern is to use a React context for this. A fairly similar example to the Vue.js plugin documentation you’ve linked, would be something like this:

JavaScript
JavaScript

The above is fairly limiting since a user would not be able to select their own language. A more complex example example would be where a user can select their language. Here is some inspiration on how you could implement this:

JavaScript
JavaScript

Note that you don’t necessarily need a React context. If you have a library function or something similar, you can just import it into your file and use it.

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