Answer the question
In order to leave comments, you need to log in
How to implement conditional rendering in functional React component?
Good day to all!
I want to implement conditional rendering in a functional React component. I don't know how to do it in a function.
I need the corresponding imported component to be rendered depending on the state.
I wrote this logic using a ternary operator and everything works, but this code is terrible and unreadable.
I definitely need to implement this in a functional component, because I use Hooks.
import React, {useState, useEffect} from 'react';
import Header from './header/header';
import Footer from './footer/footer';
//Один из этих компонентов будет рендерится между Хэдером и Футером ↓
//Название компонента в состоянии (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;
Answer the question
In order to leave comments, you need to log in
You can drop each component into the view dictionary
const COMPONENTS = {
enterProfile: EnterProfile,
personalArea: PersonalArea,
// ...
}
return COMPONENTS[activeItem];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question