algi
algi

Reputation: 577

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!

Upvotes: 7

Views: 4615

Answers (2)

Ross Allen
Ross Allen

Reputation: 44880

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:

Upvotes: 10

hiphapis
hiphapis

Reputation: 150

this code is work.

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

See the documentation for more information.

Upvotes: 6

Related Questions