Home > Mobile >  React; rendering components from an array depending on what tab im in
React; rendering components from an array depending on what tab im in

Time:10-19

What I want my code to do

I need to make tabs that display different components depends on the state

My issue

I don't know how to render the correct component using a conditional depending on what tab I'm in with react

What my code is doing so far

  • I have an array of all my components in the const allTabs
  • depending on what button i click the state of tabNum changes

import React, {useState} from "react";

import Tabcomp1 from './../components/tabcomp1';
import Tabcomp2 from './../components/tabcomp2';

const allTabs = [Tabcomp1, Tabcomp2];

const Pagetwo = () =>{
const[tabNum, setTabNum] = useState("0");
const changeTab = (e) =>{
    e.preventDefault();
    if (tabNum === "0") {
        setTabNum("1");
        console.log(tabNum);
    }
    else {
        setTabNum("0");
        console.log(tabNum);
    }
}

return(
    <div>
        <h1>you are now on page 2</h1>
        {/* tab1 */}
        <button id={0} onClick={changeTab}>tab 1</button>
        {/* tab2 */}
        <button id={1} onclick={changeTab}>tab 2</button>
        <br />
        {/* display the correct component here  */}
    </div>
)
}

export default Pagetwo;

CodePudding user response:

in you button event handler you can set index as

onClick={() => setTabNum(0 // tab index here)}

and below you button you can render it like

{allTabs[tabNum]}
  • Related