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!

2
  • 1
    Right now that syntax doesn't work but may in the future. ssorallen's answer is correct; module systems are recommended. Commented Mar 19, 2014 at 17:01
  • As @BenAlpert alluded to earlier, 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. Commented Sep 11, 2014 at 7:11

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation! I'll definitely take a look.
6

this code is work.

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

See the documentation for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.