Harsh Nagalla
Harsh Nagalla

Reputation: 1245

Globally importing react rather than importing in each component [React Hooks]

I am wondering if there is a way to provide React globally rather than importing it in each component

I have tried configuring my webpack.config.js with a provider function but it doesn't seem to work.

Webpack code

plugins: [
   new webpack.ProvidePlugin({
     'React':     'react'
   })
],

It would be great to have a suggestion for this as it gets a bit redundant to import it in each component.

Upvotes: 0

Views: 875

Answers (2)

Filip Zdjelar
Filip Zdjelar

Reputation: 21

You need to add new plugin in webpack.config.js :

 plugins: [
    new webpack.ProvidePlugin({
      React: 'react',
    }),
  ]

Also if you are using TypeScript you should add this in tsconfig.json :

 "allowUmdGlobalAccess": true

Upvotes: 0

theWellHopeErr
theWellHopeErr

Reputation: 1872

In React, there is no global importing but we can avoid importing react in every file by these two indirect methods.

  1. Creating a Higher Order Component and wrapping your other components within it.
  2. Passing the components as a prop.

Refer to this answer for more details and an example.

Upvotes: 1

Related Questions