'How to assign fields to each tab in WP Gutenberg TabPanel

I know it's a simple question, but I am new in the React and WP Gutenberg world. I am trying to create a plugin settings page using Gutenberg Components.

The tabs working fine and i know how to render fields, but i can't figure out how to assign to each tab the fields i want.

Here is the sample code:

import { TabPanel } from '@wordpress/components';
 
const onSelect = ( tabName ) => {
    console.log( 'Selecting tab', tabName );
};
 
const MyTabPanel = () => (
    <TabPanel
        className="my-tab-panel"
        activeClass="active-tab"
        onSelect={ onSelect }
        tabs={ [
            {
                name: 'tab1',
                title: 'Tab 1',
                className: 'tab-one',
            },
            {
                name: 'tab2',
                title: 'Tab 2',
                className: 'tab-two',
            },
        ] }
    >
        { ( tab ) => <p>{ tab.title }</p> }
    </TabPanel>
);


Solution 1:[1]

The Developer guide for Tab Panel mentions that tabs is an array of objects, which new properties can be added to. By adding a new property, eg content to each of your tab objects, additional components can be set to render for each tab. The simple example uses ( tab ) => <p>{ tab.title }</p> but this could also include your own custom/existing components defined in content, eg:

import { Button, TabPanel } from '@wordpress/components';

const onSelect = (tabName) => {
    console.log('Selecting tab', tabName);
};

const MyTabPanel = () => (
    <TabPanel
        className="my-tab-panel"
        activeClass="active-tab"
        onSelect={onSelect}
        tabs={[
            {
                name: 'tab1',
                title: 'Tab 1',
                className: 'tab-one',
                content: <p>Some content goes here</p>
            },
            {
                name: 'tab2',
                title: 'Tab 2',
                className: 'tab-two',
                content: <MyCustomComponent />
            },
        ]}
    >
        {({ title, content, className }) => <div className={className}><h3>{title}</h3>{content}</div>}
    </TabPanel>
);

const MyCustomComponent = () => {
    return <><p>Here is a button</p><Button variant="secondary">Click me!</Button></>;
}

The children function (given as anonymous function, above </TabPanel>) renders the tabviews by passing in the active tab object, which now includes the extra content for the tab. The output of the example above is: Tabs Example output

Aside from the Developer Guide, the Gutenberg source code is a good place to look for other examples of how TabPanel component can be implemented.. Hope this helps you with adding fields to your tabs..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S.Walsh