2

I wanna use 'if' in react router for check user is login but i don't know about correct syntax:

const RouteWithSubRoutes = (route) => (
  <Route exact path={route.path} render={props => (
      <route.component {...props} routes={route.routes} render = {props => (
          fakeAuth.isAuthenticated != true ? (
              <Redirect to={{
                pathname: '/signIn',
                state: { from: props.location }
          }}/>
          )
      )}/>
  )}/>
);

in this sample i wanna check if fakeAuth.isAuthenticated != true then redirect

2 Answers 2

3

In order to conditionally render an element please use the logical AND && or a ternary operator, returning falsy value (null, false, undefined, etc.) when the condition is not met. React won't render nulls, undefined values, and false booleans.

fakeAuth.isAuthenticated != true ? (
  <Redirect to={{
    pathname: '/signIn',
    state: { from: props.location }
  }}/>
) : null

If you just want to render an element or not - then use {condition && <Element />} syntax, or when you want to render different components based on some condition then use ternary: {condition ? <ElementA /> : <ElementB />}.


const Redirect = () => <div>Redirect</div>

const TernaryExample = ({fakeAuth}) =>
<div>
{
  fakeAuth.isAuthenticated != true ? (
    <Redirect /> 
  ) : null
}
</div>

const AndExample = ({fakeAuth}) =>
<div>
{
  !fakeAuth.isAuthenticated  && <Redirect />
}
</div>

const Examples = ({fakeAuth}) =>
<div>
  <AndExample fakeAuth={fakeAuth} />
  <TernaryExample fakeAuth={fakeAuth} />
</div>
  
ReactDOM.render(
  <Examples
    fakeAuth={{isAuthenticated: false}}
  />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />

Sign up to request clarification or add additional context in comments.

Comments

0

Your code is fine you forgot the else part.

 const RouteWithSubRoutes = (route) => (
 <Route exact path={route.path} render={props => (
  <route.component {...props} routes={route.routes} render = {props => 
 (
      fakeAuth.isAuthenticated != true ? (
          <Redirect to={{
            pathname: '/signIn',
            state: { from: props.location }
       }} />
      ) : null //here is the else.
   )}/>
 )}/>
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.