Search code examples
reactjsreact-routergithub-pages

`window.location.href` does not work on react app when deploying on github pages


There is a similar sounding question but my problem is different.

While running the react app on localhost it navigates from the following page,

enter image description here

The submit button has the code window.location.href = "/ahana-psychometry/assessments/"; And so it navigates to the page:

enter image description here

But when I press on the submit button on the page at gh-pages, the url changes from blenderous.github.io/ahana-psychometry/create to blenderous.github.io/ahana-psychometry/assessments/. but

enter image description here

but the page displays the 404 message instead:

enter image description here


Solution

  • As you are using react router, the best way is using its methods.

    Here is an example, which describes using withRouter HOC to redirect to another page:

    import {
      withRouter
    } from 'react-router-dom'
    
    class Sample extends React.Component {
      handleSubmit = (e) => {
        ...
        this.props.history.push('/ahana-psychometry/')
      }
      render() {
        return (
          <div>
            <h1>Form</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }
    
    export default withRouter(Sample)