简体   繁体   中英

How to use ternary operator to return jsx using react?

I want to hide a component if the user is in the "/items" page.

below is my code,

function Main() {
    const isAdmin = getUser();

    return(
        <Switch>
            <Route
                exact
                path="/items"
                render={routeProps => (
                    <Layout>
                        {isAdmin ? <Items {...routeProps} />: <NotFound/>}
                    </Layout>
               )}
            />
            //other Routes
        </Switch>
    );
}


const Layout: React.FC = ({ children }) => (
    <>
        <TopBar />
            {children}
        <BottomBar />
    </>
);

Now when the user is in /items page I don't want the TopBar and BottomBar to be displayed.

how can I do it? could someone help me with this? thanks.

Change your Layout component as below:

const Layout: React.FC = ({ children }) => {
    const history = useHistory();
    const isItemsPath = history.location.pathname.includes("/items");
    return (
        <>
            {!isItemsPath && <TopBar />}
                {children}
            {!isItemsPath && <BottomBar />}
        </>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM