Skip to main content
Bumped by Community user
Tweeted twitter.com/StackCodeReview/status/762274814505709568
Bumped by Community user
added 75 characters in body
Source Link
Jeemusu
  • 141
  • 1
  • 5

I made a simple bare bones Tab component, i'm a beginner when it comes to ReactJS so any hints, tips, advice regarding the codes functionality is greatly appreciated.

I made a simple bare bones Tab component, any hints, tips, advice appreciated.

I made a simple bare bones Tab component, i'm a beginner when it comes to ReactJS so any advice regarding the codes functionality is greatly appreciated.

Source Link
Jeemusu
  • 141
  • 1
  • 5

Reactjs Tab Component

I made a simple bare bones Tab component, any hints, tips, advice appreciated.

#Tab.js Component

import React from 'react';

class Tabs extends React.Component {

    constructor() {
 
        super();

        this.state = {
            activeIndex : 0
        }
    }

    handleOnClick(key, event) {

        event.preventDefault();

        this.setState({
            activeIndex : key
        });
    }

    renderNavItem(key) {

        let tab = this.props.children[key];

        return (
            <li key={ key } className={ this.state.activeIndex == key ? 'active' : ''}>
                <a href="#" onClick={ this.handleOnClick.bind(this, key) }>{ tab.props.title }</a>
            </li>
        );
    }

    render() {

        let index = 0;
        let active = this.state.activeIndex;

        let tabs = React.Children.map(this.props.children, function (child) {
            return React.cloneElement(child, {
                active : child.props.active === true ? true : (active == index++)
            });
        });

        return (
            <div className={ this.props.className }>
                <ul className="tabs-nav">
                    { Object.keys(this.props.children).map(this.renderNavItem.bind(this)) }
                </ul>
                <div className="tabs-content">
                    { tabs }
                </div>
            </div>
        )
    }
}

class Tab extends React.Component {

    render() {

        return (
            <div className={ "tab-panel" + (this.props.active ? ' active' : '') }>
                { this.props.children }
            </div>
        )
    }
}

Tab.defaultProps = { 
    active : false 
};

export default {
  Tabs,
  Tab
};

#Usage

import React from 'react';
import {Tabs, Tab} from './Tabs';

class App extends React.Component {

    render() {

        return (      
            <Tabs className="tabs-wrapper">
                <Tab active="true" title="Tab One">Tab One content</Tab>
                <Tab title="Tab Two">
                    <div>Tab Two Content</div>
                </Tab>
            </Tabs>       
        );
    }
}

React.render(
    <App/>,
    document.getElementById('react_example')
);
    

#Example

http://jsbin.com/hajokofavu/edit?js,output