alo gon
alo gon

Reputation: 187

Declared a const outside a react component to use it in different places

I have to use ABC in different places, I use to have the same definition in this two places but the I extract it outside the component.

Is this a react way to do this or are there better ways?

 const ABC = {
    jane: 0,
    john: 1
  };

 class ProjectPage extends React.Component {
    constructor(props) {
      super(props);
      resetIdCounter();
    }

   static async getInitialProps({ query }) {
      return { query, variable:ABC[query.name] };
   }

  render() {
    //code that use ABC
  }
}

Upvotes: 1

Views: 1303

Answers (1)

Vishal Kumar
Vishal Kumar

Reputation: 340

Add a parallel file in you project, ex myConfig.js. Inside this file, export this const like

export const ABC = {
    jane: 0,
    john: 1,
 };

Then import this newly created myConfig.js in your above said react file (ProjectPage) like:

import * as myConfig from './myConfig';
// or import only what you need directly
import { ABC } from './myConfig';

Now, just use wherever you want in this file like myConfig.ABC;

Upvotes: 2

Related Questions