7

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!

Joe Lencioni
  • 10,231
  • 18
  • 55
  • 66
algi
  • 567
  • 5
  • 13
  • 1
    Right now that syntax doesn't work but may in the future. ssorallen's answer is correct; module systems are recommended. – Sophie Alpert Mar 19 '14 at 17:01
  • As @BenAlpert alluded to earlier, [JSX namespacing](https://facebook.github.io/react/blog/2014/07/17/react-v0.11.html#jsx-namespacing) was added in React 0.11.0. It is still recommended to use a module loader, but you can now use namespaces as you were hoping to in your example. – Ross Allen Sep 11 '14 at 07:11

2 Answers2

10

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:

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
6

this code is work.

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

See the documentation for more information.

hiphapis
  • 151
  • 1
  • 9