0

i want to redirect to page "/items" if isAdmin true.

below is my code,

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

    return isAdmin ? (
        <Confirm />
    ) : (
        <NotFound />
    );
}

As seen in above code, if isAdmin true then i render confirm and if isAdmin false i am rendering NotFound.

But this will render NotFound within Parent component.

Instead i want to redirect to NotFound. How can I do it? Could someone help me with this. Thanks.

EDIT: what i have tried?

return isAdmin ? (
    <Confirm />
) : (
    <Route component={NotFound} />
);

But this still renders in same page.

i have used the same code in main component like below,

function Main() {
    return (
        <Switch>
            <Route
                exact
                path="/home"
                render={routeProps => (
                    <Layout>
                        <Home {...routeProps} />
                    </Layout>
                )}
             />
             //other routes here
             <Route component={NotFound}/> //if none of the urls match then                    //renders notfound
         </Switch>
     );
 }

how do i use something similar. thanks.

saritha
  • 619
  • 2
  • 12
  • 25

3 Answers3

1

if you're using react-router-dom react-router you can use the code like

i want to redirect to page "/items" if isAdmin true.

below is my code,

function Child(props) {
    const isAdmin = getUser();

    return isAdmin ? (
       props.history.push('/confirm')
    ) : (
        props.history.push('/notFound')
    );
}

you need to have routes declared in the path /confirm & notFound in your routes.js or any where route is declared

pageNotfoUnd
  • 666
  • 10
  • 20
  • i dont have url to these. just that if user is in say "/someurl" and if isAdmin then render confirm component. if isAdmin is false then in same page display notfound – saritha Jul 23 '20 at 12:49
  • i see the word `re-direct` if redirect needs to be done routes is compulsory – pageNotfoUnd Jul 23 '20 at 12:53
0

const Child = (props) => {
    const isAdmin = getUser();
    return (props.history.push(isAdmin ? '/confirm' : '/notFound');
}

You need to use history.push.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

You can use Redirect from react-router-dom.

import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = () => {
    const isAdmin = getUser();
    return (
        <Route render={isAdmin ? (
            <Redirect to='/confirm' />
        ) : (
                <NotFound />
            )
        } />
    )
}

You can similarly use a Router Switch statement. Implementation can be found in the react router doc: https://reactrouter.com/web/api/Switch

Alternatively, you may use history.push('/404'). You can find more info under this question: How to push to History in React Router v4?