Olufsen
Olufsen

Reputation: 160

ReactJS: How do I go the next page after condition is true?

After the conditions are met how does it automatically redirect to next page?

handleSubmit = event => {
     event.preventDefault();
        const { data } = this.state
        const tabletopModel = data['token']
        const newData = tabletopModel ? tabletopModel.all() : null
        console.log('log for newdata', newData)


        var c = 0;

        if (newData == null) {
            console.log('null')
        }
        else {

            for (var i = 0; i < newData.length; i++) {
                if (newData[i].ID == this.input.value) {
                    c++;
                    //console.log('i', i);
                }

            }
            if (c > 0)
            alert('Your username is: ' + this.input.value);
            //GO TO NEXT PAGE
            else { 
                alert('Invalid login');
            }
        }


    };

this is the code a button exists and when clicked it will run this part

is this right or is there a better solution?

Upvotes: 0

Views: 1274

Answers (2)

Puneet Bhandari
Puneet Bhandari

Reputation: 356

There are 2 ways by which you can move to next page

  1. If you are using react-router then use history to redirect

this.props.history.push("/yourPath")

  1. If you are not getting history in props then you can use JS method for redirection

window.location.href="/yourPath"

Upvotes: 1

ABBAS mhs
ABBAS mhs

Reputation: 109

You can use this.props.history.push if you're in a class component or props.history.push if it's a functional component, You can also pass state to the page you are redirecting to, like:

this.props.history.push({
  pathname: '/next-page',
  state: { from: "prev-page" }
})

The passed state will be stored in props.location.state in next-page,

You can also replace this:

for (var i = 0; i < newData.length; i++) {
    if (newData[i].ID == this.input.value) {
        c++;
        //console.log('i', i);
    }
}

with this:

if(newData.some(currentValue => currentValue.ID === this.input.value)) {
    c++;
    //console.log('i', i);
}

Upvotes: 1

Related Questions