NIHIR AGARWAL
NIHIR AGARWAL

Reputation: 71

Conditional Redirect on props status

I want to redirect the page if the length of props.fields is zero. But the problem it is getting rendered twice so when the it is empty it gets redirected and doesn't wait for the second time. I am new to React, it would be great if someone could help me.I have spent hours on fixing this.

import React, { Component, useEffect, useState } from 'react'
import Field from './field'
import {Redirect} from 'react-router-dom'





export default function FieldList(props) {

    const [redirect,setRedirect] = useState(false);
    useEffect(()=>{
        if(props.fields.length===0) {
            setRedirect(true)
        }
        else
            setRedirect(false)
    },[props.fields])
    
         return (
                <div>
                <h1 style={{textAlign:"center", margin:"20px 0"}}>{props.text}</h1>
                
                <div className='field-list'>
                {props.fields.map((name) => (
                    <Field name={name}  />
                ))}
                </div>
                {redirect && <Redirect to={'/'} />}
            </div>
            )
        
}

Upvotes: 2

Views: 456

Answers (2)

Yaya
Yaya

Reputation: 4838

you can instead of Redirect either use a custom browser history or use react-router-dom's useHistory hook

to use useHistory hook

import {useHistory} from 'react-router-dom'

and then at theuseEffect

   useEffect(()=>{
       if(props.fields.length===0) {
        useHistory().push('/')
        }
      },[props?.fields]
    )

if you don't want to use that, here is what you can do to create a custom browser history

first create a file and call it History.js

add this line of code to it

import { createBrowserHistory } from "history";
export default createBrowserHistory(); 

and then import it to the file

  import history from "FILE_PATH"

   useEffect(()=>{
       if(props.fields.length===0) {
        history.push('/')
        }
      }
    )

Upvotes: 2

Ardalan
Ardalan

Reputation: 848

You should change your jsx to

            <div>
                <h1 style={{textAlign:"center", margin:"20px 0"}}>{props.text}</h1>
                
                <div className='field-list'>
                {props.fields.map((name) => (
                    <Field name={name}  />
                ))}
                </div>
                {redirect ? <Redirect to={'/'} /> : null}
            </div>

Upvotes: 0

Related Questions