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

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

Creating a Sudoku puzzle grid with HTML and CSS - a step-by-step guide

Apologies for the basic inquiry, but I have created a sudoku grid with the following structure. Modified(Using Tables): <table id="grid" border="1" style="border-collapse: collapse;"> <tr class="row"> ...

"Sequencing time with Postgres, manipulating views with Angular

I am encountering issues with displaying graphs in AngularJS. My backend is written in nodeJS and includes an aggregator as a buffer for data received from netdata, which is then inserted into the database using a cron job. Now, with a new client request, ...

Get rid of all numbers from a jQuery selection except for the first and last

I am dealing with an array let numberArray = ["500", "600", "700", "800", "900", "1000", "1100", "1200"] My objective is to remove all elements except for the first and last ones. The challenge arises when the array contains only one value, as I must ens ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

React-redux is experiencing some interference from Material-ui TextField

In my React component, I have a TextField that looks like this: <TextField hintText="name" floatingLabelText="Your name:"/> This component is linked to the store using a container created with the connect function from react-redux. Currentl ...

What is the best way to halt Keyframe Animation once users have logged in?

To enhance user engagement, I incorporated keyframe animation into my login icon on the website. The main objective is to capture the attention of visitors who are not registered users. However, once a user logs in, I intend for the keyframe animation to c ...

Attempting to forward an image in a node-js/express application

I am facing an issue with a broken image link when trying to access it through Express: app.get('/fileThumbnail', function(req, res) { var url = proxiedURL +"?" + querystring.stringify(req.query); logger.info('/fileThumbnail going to url& ...

A web application using JavaScript and Node.js with a focus on creating a REST

After extensive research, I am eager to develop a web application using JavaScript and Node.js with an SQL back-end. However, the abundance of frameworks and tools available has left me feeling overwhelmed. While I have identified some that I would like to ...

Encountering issues with the routing in my live Node.js project: ERROR

I am encountering issues with my project in production. I suspect it could be due to a misconfiguration or something similar. Could you please review the provided code snippets and see if you notice any potential issues? The project works fine locally, bu ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

What is the best way to organize the table by date when not all dates are filled in?

**Issue with React-Table Sorting:** I'm encountering an issue with my React-Table implementation. I am using version 7 of the plugin. { Header: 'DATE', accessor: 'DATE', sortType: (rowA, rowB) => { ...

Importing partial peer dependencies in Npm

I have a custom npm package with a peer dependency on element-ui. This package is importing the Pagination component from element-ui: import {Pagination} from 'element-ui';' However, when I import this component in my project, the entire ...

Error: The method 'text.substr' is not a valid function

Seeking assistance with creating a reusable component for implementing a readmore function in my application. I've encountered an issue that I can't seem to figure out. Could this be a specific feature of NextJS? Any insights or suggestions would ...

Difficulty parsing JSON in MVC .Net Core Controller

I am dealing with a Web Application built in ASP.Net Core 5 that communicates with a Web API in .Net Core. The data returned from the API in JSON format needs to be read from a file named landing.js. Despite the data being stored in the variable (data), I ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

Securing multiple routes in AngularJS using resolve for authentication

How can I authenticate users for all routes in my application without having to specify it individually? Is there a global way to handle authentication for all routes, so that I don't have to include the following code on each $routeProvider.when() c ...

Unable to access variables beyond the function scope results in an undefined value

I'm currently working with an npm package that shortens URLs but I'm struggling because there isn't much documentation available. The package takes the "this.src" URL and shortens it, but when I try to use the "url" element in HTML, it retur ...