React.js: Composing components to create tabs

Viewed 18549

I’m trying to make a tabs component. TabsSwitcher and TabsPanel must be separate components so they could be used anywhere in DOM, e.g. TabsSwitcher doesn’t have to be followed by TabsPanel.

To make it work, I need to somehow connect these components. Furthermore, TabsSwitcher must be able to tell TabsPanel when a tab was clicked.

/** @jsx React.DOM */

var TabsExample = React.createClass({
    render: function() {
        var tabs = [
            {title: 'first', content: 'Content 1'},
            {title: 'second', content: 'Content 2'}
        ];
        return <div>
            <TabsSwitcher items={tabs}/>
            <TabsContent items={tabs}/>
        </div>;
    }
});

var TabsSwitcher = React.createClass({
    render: function() {
        var items = this.props.items.map(function(item) {
            return <a onClick={this.onClick}>{item.title}</a>;
        }.bind(this));
        return <div>{items}</div>;
    },
    onClick: function(e) {
        // notify TabsContent about the click
    }
});

var TabsContent = React.createClass({
    render: function() {
        var items = this.props.items.map(function(item) {
            return <div>{item.content}</div>;
        });
        return <div>{items}</div>;
    }
});

React.renderComponent(
    <TabsExample/>,
    document.body
);

What’s the best way to do it?


Solution: http://jsfiddle.net/NV/5YRG9/

1 Answers
Related