saritha
saritha

Reputation: 659

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.

Upvotes: 1

Views: 137

Answers (1)

Shivang Gupta
Shivang Gupta

Reputation: 3329

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 />}
        </>
    );
}

Upvotes: 4

Related Questions