Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
¿Cómo implemento la representación condicional en un componente React funcional?

Quiero implementar la representación condicional en un componente React funcional. No sé cómo hacer esto en una función.

Necesito que se represente el componente importado correspondiente según el estado.

Escribí esta lógica usando el operador ternario y todo funciona, pero este código es terrible e ilegible.

 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;

Definitivamente necesito implementar esto en el componente funcional, porque uso ganchos.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Qué tal si

 const ComponentMap = { landing: Landing, bookingManagement: BookingManagement, bookingTickets: BookingTickets, enterProfile: EnterProfile, personalArea: PersonalArea, register: Register, searchResults: SearchResults, choosePlace: ChoosePlace }; function App() { const [activeItem, setActiveItem] = useState("landing"); useEffect(() => { console.log(activeItem); }); const ActiveComponent = ComponentMap[activeItem] || React.Fragment; const ActiveComponentProps = {}; if (activeItem === "landing") { ActiveComponentProps.changeMain = setActiveItem; } return ( <> <Header changeMain={setActiveItem} /> <ActiveComponent {...ActiveComponentProps} /> <Footer changeMain={setActiveItem} /> </> ); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

en vez de

 {(activeItem=='landing' ? ( <Landing changeMain={setActiveItem}/> ) : ( <></> ))}

ir con

 {activeItem=='landing' && ( <Landing changeMain={setActiveItem}/> )}
about 4 years ago · Juan Pablo Isaza Denunciar

0

puedes ir con la implementación del enrutador de reacción. O si desea manejar lo mismo en este componente, puede hacer algo similar a continuación

 const getComponent = () => { if (condition1) { return <Component1/> } else if (condition2) { return <Component2/> } return <DefaultComponent/> }

y dentro del retorno de representación puede llamar a esa función como se muestra a continuación

 return ( {getComponent()} )
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda