React.js: Is it possible to namespace child components while still using JSX to refer to them?

StackOverflow https://stackoverflow.com/questions/23653616

  •  22-07-2023
  •  | 
  •  

Pregunta

So let's say I have a component called ImageGrid and it is defined as below:

window.ImageGrid = React.createClass({
    render: function() {
        return (
            <div className="image-grid">
                <ImageGridItem />
            </div>
        );
    }
});

As you can see it includes a child react component called ImageGridItem. Which is defined below.

window.ImageGridItem = React.createClass({
    render: function() {
        return (
            <div className="item-container">something</div>
        );
    }
});

This works fine as long as both are directly properties of window. But this is kind of horrible so I'd like to group up all my react components under a namespace of window.myComponents for example.

So the definitions change to:

window.myComponents.ImageGrid     = React.createClass({...});
window.myComponents.ImageGridItem = React.createClass({...});

The problem now is that as ImageGrid refers to <ImageGridItem /> in it's render() function, the JS version of this gets compiled out to JS as ImageGridItem() which of course is undefined since it's now actually myComponents.ImageGridItem() and react complains it can't find it.

Yes I realise I can just not write JSX for that component include and manually do myComponents.ImageGridItem({attr: 'val'}) but I'd really prefer to use the JSX html syntax shortcut as it's much easier to read and develop with.

Are there any ways to get this to work while still using the <ImageGridItem /> syntax for children? And if not is it possible to define the JS namespace within the JSX?

¿Fue útil?

Solución

This pull request was just merged:

https://github.com/facebook/react/pull/760

It allows you to write things like <myComponents.ImageGridItem /> in React 0.11 and newer.

That said, a proper module system is the recommended way to manage dependencies to avoid pulling in code that you don't need.

Otros consejos

Currently, there isn't a way to do this. Namespacing with JSX is on the todo list.

Most people use some kind of module system (browserify, webpack, requirejs), which replace namespacing and allow components to be used easily. There are a lot of other benefits, so I very much recommend looking into it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top