Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfiddle.net/6719phr3/1/

import React, { useState, useCallback } from "react";
import { Tabs, Button } from 'antd';
import 'antd/dist/antd.css';

const { TabPane } = Tabs;

const Tabbar = (props) => {

const [focusingPaneKey, setFocusingPaneKey] = useState('');
const [openingPaneKeys, setOpeningPaneKeys] = useState([]);

const openPane = (paneKey) => {
  setOpeningPaneKeys(oldState => {
    if (!oldState.includes(paneKey)) {
      return [...oldState, paneKey];
    }
    return oldState;
  });

  setFocusingPaneKey(paneKey);
}

const closePane = (paneKey) => {
  if (paneKey === focusingPaneKey) {
    const paneKeyIndex = openingPaneKeys.indexOf(paneKey);
    setFocusingPaneKey(openingPaneKeys[paneKeyIndex - 1]);
  }

  setOpeningPaneKeys(openingPaneKeys.filter((openingPaneKey) => openingPaneKey !== paneKey));
}

const handleTabsEdit = useCallback((key, action) => {
  if (action === 'remove') {
    closePane(key);
  }
}, [closePane]);

const { panes } = props;
const keysOfPane = Object.keys(panes);

return (
<div className="tab-section">
  <div style={{ marginBottom: 16 }}>
    {keysOfPane.map((key) => (
      <Button key={key} onClick={() => openPane(key)}>
        ADD Tab-{key}
      </Button>
    ))}
  </div>
  <Tabs
    hideAdd
    onChange={openPane}
    activeKey={focusingPaneKey}
    type="editable-card"
    onEdit={handleTabsEdit}
  >
    {openingPaneKeys
      .map((key) => panes[key])
      .map((pane) => (
        <TabPane tab={pane.title} key={pane.key}>
          {pane.content}
        </TabPane>
      ))}
  </Tabs>
</div>
)
}

export default Tabbar

Answer №1

TabPane accepts tab as ReactNode,

https://ant.design/components/tabs/

 <Tabs
  hideAdd
  onChange={openPane}
  activeKey={focusingPaneKey}
  type="editable-card"
  onEdit={handleTabsEdit}
>
  {openingPaneKeys
    .map((key) => panes[key])
    .map((pane) => (
      <TabPane
        tab={
          <span>
            <AppleOutlined />
            {pane.title}
          </span>
        }
        key={pane.key}
      >
        {pane.content}
      </TabPane>
    ))}
</Tabs>;

Try this

var x = {
  1: { key: "1", title: "Tab 1", content: "Content of Tab Pane 1" },
  2: { key: "2", title: "Tab 2", content: "Content of Tab Pane 2" },
  3: { key: "3", title: "Tab 3", content: "Content of Tab Pane 3" },
};

const map = {
  1: Icon1,
  2: Icon2,
  3: Icon3,
};

const getTab = (pane) => (
  <TabPane
    tab={
      <span>
        <pane.icon />
        {pane.title}
      </span>
    }
    key={pane.key}
  >
    {pane.content}
  </TabPane>
);

<Tabs
  hideAdd
  onChange={openPane}
  activeKey={focusingPaneKey}
  type="editable-card"
  onEdit={handleTabsEdit}
>
  {Object.keys(x).map((key) =>
    getTab({
      ...panes[key],
      icon: map[key],
    })
  )}
</Tabs>;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with "return false" not functioning properly in jQuery ajax calls

I have been developing a registration form using jQuery ajax. Below is the code snippet I am working with: function validateData() { var email = jQuery("#email").val(); var username = jQuery("#username").val(); var emailReg = /^([\w-&bsol ...

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

What is the process for obtaining authorization to access user information?

I am facing a perplexing issue with my app settings. Despite setting everything up correctly, I am unable to authenticate my account on my website using the Javascript SDK. Whenever I try to console.log(me), I only receive public information. Upon furthe ...

Is it possible for me to convert a .map array into a comma-separated array enclosed in double quotation marks?

I am attempting to extract data from a group of twig variables and convert them into a javascript plugin. The data consists of dates listed in an array format. Initially, they are displayed on the template as a string like this: {"date":"2018-08-30, 2018- ...

Creating an interactive checkbox input field utilizing a JSON-driven database

Can someone assist me with creating dynamic checkboxes? I have JSON data structured as follows: [ { "categoryName": "Category 1", "items": [ { "value": "value1", "label": "label1" }, { "value": "value2" ...

Switching button class when hovering over another div

When you click on the "collapsible-header" div, I want the text "TE LAAT" in the button to change to "NU BETALEN". Currently, the CSS code changes the text on hover, but I want it to change on click when the collapsible-header also has the active class. T ...

Learn how to dynamically set the "selected" option in Vue based on object data

I've done some digging on SO but haven't found exactly what I need. So, here's the situation - I've got a sorting function in progress. I have an array of date ranges (PayPeriods) that I want to render into a select with option compone ...

Changing the background color using jQuery switch case statement

I am attempting to utilize jquery to dynamically change the background image of a webpage based on different cases in a JavaScript switch statement. I have completed three steps: 1) Included this script tag in my HTML document: <script src="http://co ...

The subsequent block within the code is being initiated following the initial block in Node.js

It was expected that "1" would be printed before "2", but the output is incorrect. fs.readdir("./my_stocks", (err, files) => { for(each in files){ var file=files[each]; if(file!='portfolio.js'){ var fn="./my_sto ...

Trouble arises when extending an MUI component due to a TypeScript error indicating a missing 'css' property

We have enhanced the SnackbarContent component by creating our own custom one called MySnackbarContent: export interface MySnackbarContentProps extends Omit<SnackbarContentProps, 'variant'> { variant?: MyCustomVariant; type?: MyCustomTy ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

Learn how to dynamically highlight a table row when any changes are made to it using jQuery

Is there a way to automatically highlight the current table row when any input text or image is changed within that specific row using jQuery? In the given code snippet below, with two rows provided, how can one of the rows be highlighted upon modifying ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Select component experiencing misalignment of MaterialUI labels

My modal component is displaying a form with text inputs and select components, but the Select Labels are appearing at the top left corner of the form. I tried a solution from here, but it didn't work for me. Another issue is that when I click on one ...

Steps for rendering a PNG image encoded in base64 format within a React project

I am currently working on a project that involves fetching an image from an API and then embedding it into an <img> tag. The API sends the image in a png format, which I then convert to base 64 format. When I print out the contents of the image, it a ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Trouble with CSS and JS tabs not activating when clicked?

I am experiencing issues with a navigation (organized in tabs) that is not functioning on this page, but it works correctly on this page using the same method for inclusion. When clicking "Norway" on the top left, the navigation opens but switching to the ...

Dynamic divs to occupy the rest of the available vertical area

I have been experimenting with a new website layout and created a form setup. However, I am facing an issue with the fluidity of the layout. While the items are floating into position, there is a problem where if the item on the right is 400px bigger than ...