Saturday, December 28, 2019

Implementing Programically Redirect With React Router | React redirect to component | Redirect with React Router

A lot of these short blog posts are just for me to find later when I forget how to do something.
So, there is an span where there is a click event named goToAnotherPage, when clicked I just set state the edit variable true, and it redirect to another page using react component named Redirect as described in function goToAnotherPage.
import React, { Component } from 'react'
import {Redirect} from 'react-router-dom'

class SomePage extends Component {
    constructor () {
        super();
        this.state = {
            edit: false
        };
        this.goToAnotherPage = this.goToAnotherPage.bind(this);
    }

    componentDidMount () {
        super.componentDidMount();
    }

    goToAnotherPage(e) {
        this.setState({'edit': true});
    }

    render () {
        if (this.state.edit) {
            return <Redirect to={'/go-to-another-page'} push={true}/>
        }
        return (
            <span onClick={(e) => this.goToAnotherPage(e)}>Go to another page</span>
        )
    }
}

export default SomePage

No comments:

Post a Comment