Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: React and global namespace pollution

I'm considering to use react in a new website and I'm still wondering, how to handle the global namespace with react components. For example, if I define several React Components like this:

var MySlider = React.createClass({ // snip });
var MyAlert = React.createClass({ // snip });
var MyDropdown = React.createClass({ // snip });

Rendering a component would look like this:

React.renderComponent(
    <MySlider />,
    document.getElementById('content')
);

However, I'd prefer to namespace my components to avoid polluting the global namespace.

var Namespace = {};
Namespace.MySlider = React.createClass({ // snip });

When it comes to rendering, the component is not found due to namespacing, I guess.

React.renderComponent(
    <Namespace.MySlider />, // component is not found
    document.getElementById('content')
);

What am I missing here? Just ignore global namespace pollution? Or is there a possibility to namespace your components?

Thanks!

like image 536
algi Avatar asked Mar 19 '14 08:03

algi


Video Answer


2 Answers

This is not exactly a React JS question since any large JavaScript codebase has to deal with module loading. I suggest forgoing namespacing in JavaScript the way you started to approach it and instead use a module loader.

You will get many opinions on this, but look at some of the widely-used module loaders:

  • Browserify
  • rollup.js
  • Webpack
like image 102
Ross Allen Avatar answered Nov 05 '22 07:11

Ross Allen


this code is work.

React.renderComponent(
    Namespace.MySlider(),
    document.getElementById('content')
);

See the documentation for more information.

like image 39
hiphapis Avatar answered Nov 05 '22 05:11

hiphapis