Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-dyn-tabs

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-dyn-tabs

React dynamic tabs with full API

  • 4.2.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
216
decreased by-31.65%
Maintainers
1
Weekly downloads
 
Created
Source

react-dyn-tabs

React Dynamic Tabs with full API

Demo

Features

  • Based on React hook
  • Open & Close & Select & Refresh
  • lazy/eager loading
  • Customizable style
  • Full API
  • Return to last used tab when closing selected tab
  • PanelList can be rendered outside the TabList container
  • ARIA accessible
  • Supporting custom Tab component
  • Batching updates

Table of Contents

Installation

$ npm install react-dyn-tabs --save

or

$ yarn add react-dyn-tabs

Basic Example

import React, {useEffect} from 'react';
import useDynTabs from 'react-dyn-tabs';
import 'react-dyn-tabs/style/react-dyn-tabs.css';
import 'react-dyn-tabs/themes/react-dyn-tabs-card.css';
import ContactComponent from './contact-component';

export default () => {
  const options = {
    tabs: [
      {
        id: '1',
        title: 'home',
        closable: false,
        panelComponent: (porps) => <p> home content </p>,
      },
      {
        id: '2',
        title: 'contact',
        panelComponent: ContactComponent, // or can be <ContactComponent />
      },
    ],
    selectedTabID: '1',
    onLoad: function () {},
  };
  const [TabList, PanelList, ready] = useDynTabs(options);
  useEffect(() => {
    ready((instance) => {
      // open more tabs
      instance.open({id: '3', title: 'Tab 3', panelComponent: (porps) => <p> Tab 3 content </p>});
      instance.open({id: '4', title: 'Tab 4', panelComponent: (porps) => <p> Tab 4 content </p>});
      // switch to new tab
      instance.select('4');
    });
  }, []);
  return (
    <div>
      <TabList></TabList>
      <PanelList></PanelList>
    </div>
  );
};

ready function

  • ready function is returned by useDynTabs hook.

  • ready function accepts a function as a parameter and calls it with instance object after the first render, when the component is mounted.

  • Tabs can't be manipulated safely before the first render, use ready() to make a function available after the component is mounted.

  • ready function can be called multiple times

  • ready function and instance Object will not be changed after re-rendering multiple times.

  • When ready function is called after the first render, it calls its function parameter with instance object immediately.

Options

tabs

typedefault valuerequireddescription

Array of tabData

[]falseinitial opened tabs

Example

const [TabList, PanelList, ready] = useDynTabs({
  tabs: [
    {
      id: '1',
      title: 'home',
      iconClass: 'fa fa-home',
      closable: true,
      panelComponent: (porps) => <p> home content </p>,
    },
    {
      id: '2',
      title: 'contact',
      tooltip: 'contact',
      disable: true,
      closable: false,
      panelComponent: (porps) => <p> contact content </p>,
    },
  ],
});

selectedTabID

typedefault valuerequireddescription
string' 'falseinitial selected tab id

Example

const [TabList, PanelList, ready] = useDynTabs({
  tabs: [
    {
      id: '1',
      title: 'home',
      iconClass: 'fa fa-home',
      closable: true,
      panelComponent: (porps) => <p> home content </p>,
    },
    {
      id: '2',
      title: 'contact',
      tooltip: 'contact',
      disable: true,
      closable: false,
      panelComponent: (porps) => <p> contact content </p>,
    },
  ],
  selectedTabID: '2',
});

direction

typedefault valuerequireddescription
string'ltr'falsecan be either of 'ltr' or 'rtl'

Example

const [TabList, PanelList, ready] = useDynTabs({direction: 'rtl'});

tabComponent

typerequireddescription
React componentfalsecustom tab component

Example

const [TabList, PanelList, ready] = useDynTabs({
  tabComponent: (props) => {
    const {id, isSelected, api: instance} = props;
    return (
      <button {...props.tabProps}>
        {props.children}
        {props.iconProps && <span {...props.iconProps}></span>}
      </button>
    );
  },
});

defaultPanelComponent

Default value for panelComponent option.

typerequireddescription
React component | React elementfalse

Example

const [TabList, PanelList, ready] = useDynTabs({
  defaultPanelComponent: (props) => {
    const {id, isSelected, api: instance} = props;
    return <div></div>;
  },
});

accessibility

typedefault valuerequireddescription
booleantruefalse

Example

const [TabList, PanelList, ready] = useDynTabs({accessibility: false});

NOTE :

This option assigns id attribute on panel element and button element inside the tab. for having elements without id attribute, set this option to false.

isVertical

typedefault valuerequireddescription
booleanfalsefalse

Example

const [TabList, PanelList, ready] = useDynTabs({isVertical: true});

onLoad

typerequireddescription
functionfalseThis event is fired only once, after first render

Example

const [TabList, PanelList, ready] = useDynTabs({
  onLoad: function () {
    // you can use 'this' here which refers to the instance
  },
});

onInit

typerequireddescription
functionfalseThis event is triggered after every render.

Example

const [TabList, PanelList, ready] = useDynTabs({
  onInit: function () {
    // you can use 'this' here which refers to the instance
  },
});

onChange

typerequireddescription
functionfalsefires when we open|close|select a tab. this event is not fired initially

Example

const [TabList, PanelList, ready] = useDynTabs({
  onChange: function ({currentData, previousData, closedTabIDs, openedTabIDs}) {
    // you can use 'this' here which refers to the instance
  },
});

beforeSelect

typerequireddescription
functionfalse fires when the user clicks on the tab, but before select them. This event should return boolean true or false, If the event return false the tab is not selected.

Example

const [TabList, PanelList, ready] = useDynTabs({
  beforeSelect: function (e, id) {
    // you can use 'this' here which refers to the instance
    return true;
  },
});

onSelect

typerequireddescription
functionfalsefires after selecting tabs. this event is not fired initially

Example

const [TabList, PanelList, ready] = useDynTabs({
  onSelect: function ({currentSelectedTabId, previousSelectedTabId}) {
    // you can use 'this' here which refers to the instance
  },
});

onOpen

typerequireddescription
functionfalsefires after opening tabs. this event is not fired initially

Example

const [TabList, PanelList, ready] = useDynTabs({
  onOpen: function (openedTabIDs) {
    // you can use 'this' here which refers to the instance
  },
});

beforeClose

typerequireddescription
functionfalse fires when the user clicks on the close icon, but before close them. This event should return boolean true or false, If the event return false the tab is not closed.

Example

const [TabList, PanelList, ready] = useDynTabs({
  beforeClose: function (e, id) {
    // you can use 'this' here which refers to the instance
    return true;
  },
});

onClose

typerequireddescription
functionfalsefires after closing tabs. this event is not fired initially

Example

const [TabList, PanelList, ready] = useDynTabs({
  onClose: function (closedTabIDs) {
    // you can use 'this' here which refers to the instance
  },
});

onDestroy

typerequireddescription
functionfalsefires before destroying useDynTabs hook

Example

const [TabList, PanelList, ready] = useDynTabs({
  onDestroy: function () {
    // you can use 'this' here which refers to the instance
  },
});

Methods

isOpen

Return value : boolean

Parameters:

  • id: String

Example

const result = instance.isOpen('tab ID');

open

Triggers 'onInit', 'onChange' and 'onOpen' event. opening an already opened tab only triggers 'onInit' event.

Return value : Promise

Parameters:

  • tabData: Object

Example

if (instance.isOpen('contact') == false) {
  instance
    .open({
      id: 'contact',
      title: 'contact',
      tooltip: 'contact',
      disable: false,
      closable: true,
      iconClass: '',
      panelComponent: <ContactPanel></ContactPanel>,
    })
    .then(({currentData, instance}) => {
      console.log('contact tab is open');
    });
}

isSelected

Return value : boolean

Parameters:

  • id: String

Example

const result = instance.isSelected('tab ID');

select

Makes current and previous selected tab to be re-rendered

Triggers 'onInit', 'onChange' and 'onSelect' event.

Selecting an already selected tab only triggers 'onInit' event.

Return value : Promise

Parameters:

  • id: string

Example

if (instance.isSelected('1') == false) {
  instance.select('1').then(({currentData, instance}) => {
    console.log('tab 1 is selected');
  });
}

close

Triggers 'onInit', 'onChange' and 'onClose' event.

Closing an already closed tab only triggers 'onInit' event.

It switches to the previously selected tab before closing if switching parameter was true and tab was already opened and selected.

When the user clicks on the default close icon, close function is called with true value as a switching parameter.

Return value : Promise

Parameters:

  • id: string
  • switching: boolean (default : true)

Example

if (instance.isOpen('2') == true) {
  instance.close('2').then(({currentData, instance}) => {
    console.log('tab 2 is closed');
  });
}

refresh

Makes all tabs to be re-rendered.

triggers onInit event.

Return value : Promise

Example

instance.refresh().then(({currentData, instance}) => {
  //do sth here
});

getOption

Parameters:

  • optionName : String

Example

const direction = instance.getOption('direction');
const onSelect = instance.getOption('onSelect');

setOption

You can use this method for setting all options except selectedTabID and tabs options.

For re-rendering immediately after this function, you should call refresh method after it.

Return value : instance object

Parameters:

  • optionName : String
  • optionValue : string|boolean|object|function

Example

instance.setOption('direction', 'rtl');
instance.setOption('onSelect', () => {});
instance.setOption('beforeSelect', () => false);

getTab

get tabData by id

Return value : tabData object

Parameters:

  • id : String

Example

const tabData = instance.getTab('3');
console.log(tabData.id); // 3

setTab

set tabData by id. for re-rendering immediately after this function, you should call refresh method after it.

Return value : instance

Parameters:

  • tab id : String
  • source object : containing the properties you want to apply

Example

instance.setTab('home', {disable: true});
instance.setTab('contact', {closable: false, panelComponent: (props) => <p>contact panel</p>});

on

Attach an event handler function for one event.

Return value : instance

Parameters:

  • event Name : String (can be either of onSelect|onClose|onOpen|onInit|onChange|onDestroy)
  • handler : function

Example

instance.on('onSelect', function (params) {
  const {currentSelectedTabId, previousSelectedTabId} = params;
  // can use 'this' here which refers to the instance
});

one

Attach a handler to an event. The handler is executed at most once.

Return value : instance

Parameters:

  • event Name : String (can be either of onSelect|onClose|onOpen|onInit|onChange|onDestroy)
  • handler : function

Example

instance.one('onSelect', function ({currentSelectedTabId, previousSelectedTabId}) {
  // can use 'this' here which refers to the instance
});

off

Remove an event handler.

Return value : instance

Parameters:

  • event Name : String (can be either of onSelect|onClose|onOpen|onInit|onChange|onDestroy)
  • handler : function (A handler function previously attached for the event)

Example

const onSelectHandler = function (params) {
  const {currentSelectedTabId, previousSelectedTabId} = params;
  // can use 'this' here which refers to the instance
  this.off('onSelect', onSelectHandler);
};
instance.on('onSelect', onSelectHandler);

getData

get a copy of data

Return value : Object

Example

const {selectedTabID, openTabIDs} = instance.getData();

NOTE :

  • getCopyData function is an older version of getData function and it is enabled by default so that existing users do not have to change their code. You are free to use both conventions.

getPreviousData

get a copy of data in previous render

Return value : Object

Example

const {selectedTabID, openTabIDs} = instance.getPreviousData();

NOTE :

  • getCopyPerviousData function is an older version of getPreviousData function and it is enabled by default so that existing users do not have to change their code. You are free to use both conventions.

tabData

property nametypedefault valuerequired
idstringfalse
titlestring' 'false
tooltipstring' 'false
panelComponentcan be either of React Element or React Componentfalse
closablebooleantruefalse
iconClassstring' 'false
disablebooleanfalsefalse

Example

const tabData = {
  id: 'contactID',
  title: 'contactTitle',
  tooltip: 'contactTooltip',
  disable: true,
  iconClass: 'fa fa-home',
  closable: false,
  panelComponent: (porps) => <p> contact content </p>,
};
const [TabList, PanelList, ready] = useDynTabs({tabs: [tabData]});
// or
if (instance.isOpen(tabData.id) == false) {
  instance.open(tabData).then(() => {});
}

Lazy Loading

upcoming...

Styling

react-dyn-tabs does not include any style loading by default. Default stylesheets and themes are provided and can be included in your application if desired.

import 'react-dyn-tabs/style/react-dyn-tabs.min.css';
// or import 'react-dyn-tabs/style/scss/react-dyn-tabs.scss';
import 'react-dyn-tabs/themes/react-dyn-tabs-card.min.css';
// or import 'react-dyn-tabs/themes/scss/react-dyn-tabs-card.scss';

NOTE :

You can find other themes at themes folder.

Caveats

  • Some actions like open, select, close and refresh cause re-rendering, and using them immediately after calling useDynTabs hook will create an infinite loop and other bugs that most likely you don't want to cause. you should use them inside event listeners or subscriptions.

  • Do not use setState inside the onInit callback because it leads to an infinite loop.

Deprecated features

These deprecated features can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code.

  • Third element of returned array by useDynTabs hook should not be used as an object, it is no longer recommended and only be kept for backwards compatibility purposes, may be removed in the future. Avoid using it as an object and use the code below instead of it.
const [TabList, PanelList, ready] = useDynTabs(options);
const open_tab_3 = function () {
  ready(function (instance) {
    if (instance.isOpen('3') === false) {
      instance.open({id: '3', title: 'mock tab 3'});
      instance.select('3');
    }
  });
};
  • First parameter of onSelect function is an object and has perviousSelectedTabId property which is deprecated. you should use previousSelectedTabId property instead of perviousSelectedTabId property.

  • First parameter of onChange function is an object and has perviousData property which is deprecated. you should use previousData property instead of perviousData property.

Test

$ npm run test

License

MIT

Keywords

FAQs

Package last updated on 29 Jul 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc