I want to implement conditional rendering in a functional React component. I don't know how to do this in a function.
I need the corresponding imported component to be rendered depending on the state.
I wrote this logic using the ternary operator and everything works, but this code is terrible and unreadable.
import React, { useState, useEffect } from "react";
import Header from "./header/header";
import Footer from "./footer/footer";
// One of these components will be rendered between Header and Footer ↓
// Name of the component in the state (activeItem)
import Landing from "./landing/landing";
import BookingManagement from "./bookingManagement/BookingManagement";
import BookingTickets from "./bookingTickets/bookingTickets";
import EnterProfile from "./enterProfile/enterProfile";
import PersonalArea from "./personalArea/personalArea";
import Register from "./register/register";
import SearchResults from "./searchResults/searchResults";
import ChoosePlace from "./choosePlace/choosePlace";
function App() {
const [activeItem, setActiveItem] = useState("landing");
useEffect(() => {
console.log(activeItem);
});
return (
<>
<Header changeMain={setActiveItem} />
{activeItem == "landing" ? <Landing changeMain={setActiveItem} /> : <></>}
{activeItem == "bookingManagement" ? <BookingManagement /> : <></>}
{activeItem == "bookingTickets" ? <BookingTickets /> : <></>}
{activeItem == "enterProfile" ? <EnterProfile /> : <></>}
{activeItem == "personalArea" ? <PersonalArea /> : <></>}
{activeItem == "register" ? <Register /> : <></>}
{activeItem == "searchResults" ? <SearchResults /> : <></>}
{activeItem == "choosePlace" ? <ChoosePlace /> : <></>}
<Footer changeMain={setActiveItem} />
</>
);
}
export default App;
I definitely need to implement this in the functional component, because I use hooks.