Home > Net >  Passing components as state in React (Tab functionality)
Passing components as state in React (Tab functionality)

Time:06-23

Is it possible to pass other components through a state? I'm trying to make a tab function like a web browser, and if the user clicks the tab, a component shows up.

In my app.js I have -

const[chosenTab, setChosenTab] = useState("")

return (
    <>
    <Main chosenTab = {chosenTab}/>
    </>
  );

In Main.js -

const Main = ({chosenTab}) => {
  return (
    <>
    {chosenTab}
    </>
  )
}

With the code below, the logic works to display the name of the tab/other component, but doesn't work if I replace {chosenTab} with <{chosenTab}/> to pass it as a component rather than just html.

CodePudding user response:

I don't think this would work as you've structured it - I'd be welcome to have someone prove me wrong though since that would be a neat trick.

Now if I had to solve this problem, I'd simply use a object to hold what I need:

const tabMap = {
"string1": <component1 />,
"string2": <component2 />,
"string3": <component3 />
}

const Main = ({chosenTab}) => {
  return (
    <>
    {tabMap[chosenTab]}
    </>
  )
}

Even further, let's say you wanted to pass in custom props, you could make tabMap a function to do that.

CodePudding user response:

You can pass component reference itself as a tab.

const TabA = () => <div>Tab A</div>
const TabB = () => <div>Tab B</div>

const Main = ({ ChosenTab }) => {
   retur <ChosenTab />
}

const App = () => {
    const [chosenTab, setChosenTab] = useState(() => TabA);

    const changeTab = (tab) => setChosenTab(() => tab);


    return <Main ChosenTab={chosenTab} />
}

export default App;

Or you can store your tabs in object, Map or Array and set state accordingly


const tabs = {
    A: TabA,
    B: TabB
}

const App = () => {
    const [chosenTab, setChosenTab] = useState(() => tabs.A);

    const changeTab = (tabKey) => setChosenTab(() => tabs[tabKey]);


    return <Main ChosenTab={chosenTab} />
}

export default App;
  • Related