Home > database >  How to create a Tabs component with React
How to create a Tabs component with React

Time:09-29

import { Home } from "./home";

const TABS = [
   {
     component: Home,
     label: "Home"
   }
];

export default class Tabs extends Component {
   constructor(props) {
      super(props);
      this.state = {
         "Home": {
            isActive: true
         }
      }
   }

   checkIsActive = (evt) => {
      const newState = {};

      TABS.map(tab => {
         if (evt.currentTarget.getAttribute("value") === tab.label) {
            newState[tab.label] = { "isActive": true }
         } else {
            newState[tab.label] = { "isActive": false }
         }
      })

      this.setState(newState);
   }

   render () {
      return (
         <>
            <div className="constContainer">
               <h1 className="title">Tabs</h1>
               <div className="tabs">
                  {TABS.map(tab => {
                     if (this.state[tab.label].isActive === true) {
                        return React.createElement("p", { className: "tab active", value: tab.label, key: tab.label, onClick: this.checkIsActive }, tab.label);
                     }
                     
                     return React.createElement("p", { className: "tab", value: tab.label, key: tab.label, onClick: this.checkIsActive }, tab.label);
                  })}
               </div>
            </div>
            {TABS.map(tab => {
               if (this.state[tab.label]["isActive"] === true) {
                     // HERE
               }
            })}
         </>
      )
   }
}

I've marked the section where I want to return the component with HERE. I want to use the TABS constant and use the component key to conditionally render the component. When the user clicks the paragraph tag, I want to render the component.

Below is the home file being imported in the main file:

import React from "react";

export const Home = () => {
   return (
      <div className="pageContainer">
         <h1 className="pageHeading">Home Page</h1>
         <p className="pageContent">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus egestas tellus ut sapien semper, dictum aliquet eros ultrices. Integer aliquet nulla nulla, quis sagittis erat venenatis in. Quisque at viverra urna. Proin ex nisi, pretium et posuere non, malesuada a metus. Donec est diam, efficitur eu lacus et, accumsan lobortis velit. Proin egestas tortor purus, nec congue sem tincidunt id. Mauris non urna sit amet augue varius posuere. Aliquam erat volutpat. Donec convallis pellentesque ipsum, id sodales quam ultricies non. Nullam et egestas quam, at hendrerit diam. Sed iaculis in arcu in sagittis. In eget nibh eget orci accumsan venenatis id ut mauris. Pellentesque sit amet porta lorem. Sed condimentum dignissim sollicitudin. Aliquam felis quam, dignissim in ante sed, iaculis congue nisl. Etiam sed est nunc.</p>
      </div>
   )
}

Any help is appreciated!

CodePudding user response:

You can simply extract the component from the TABS list and render it. This is a complete example of a Tabs components:

import { Home } from "./home";

const TABS = [
    {
        component: Home,
        label: "Home"
    }
];

export default class Tabs extends Component {
    constructor(props) {
        super(props);
        this.state = {
            activeTab: "Home",
        }
    }
    
    selectTab = (name) => {
        this.setState({ activeTab: name });
    }

    getActiveTab = () => {
        return TABS.find(t => t.label === this.state.activeTab);
    }
    
    render () {
        const TabComponent = getActiveTab()?.component;
        
        return (
            <>
                <div className="constContainer">
                    <h1 className="title">Tabs</h1>
                    <div className="tabs">
                        {TABS.map(tab => {
                            const isActive = this.state.activeTab === tab.label
                            return (
                                <p
                                    class={'tab'   (isActive ? ' active' : '')}
                                    onclick={() => this.selectTab(tab.label)}
                                    key={tab.label}
                                >{tab.label}</p>
                            )
                        })}
                    </div>
                </div>
                { TabComponent && <TabComponent></TabComponent> }
            </>
        )
    }
}

Side note

Try to avoid mixing JSX and raw React.createElement as it is less readable and unless specific use cases it makes no sense.

CodePudding user response:

You can use creatElement API method:

 {TABS.map(tab => {
               if (this.state[tab.label]["isActive"] === true) {
                    return React.createElement(tab.label, {});
               }
// return value for fail condition
//return null;
            })}


  • Related