HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactMajor

React-Router External link

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
externalreactlinkrouter

Problem

Since I'm using React Router to handle my routes in a React app, I'm curious if there is a way to redirect to an external resource.

Say someone hits:

example.com/privacy-policy

I would like it to redirect to:

example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

I'm finding exactly zero help in avoiding writing it in plain JavaScript at my index.html loading with something like:

if (window.location.path === "privacy-policy"){
  window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}

Solution

I actually ended up building my own Component, `.
It takes information from the
react-router element, so I can keep it in my routes. Such as:



Here is my component in case anyone is curious:

import React, { Component } from "react";

export class Redirect extends Component {
  constructor( props ){
    super();
    this.state = { ...props };
  }
  componentWillMount(){
    window.location = this.state.route.loc;
  }
  render(){
    return (Redirecting...);
  }
}

export default Redirect;


Note: This is with
react-router: 3.0.5`, it is not so simple in 4.x

Code Snippets

<Route
  path="/privacy-policy"
  component={ Redirect }
  loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
  />
import React, { Component } from "react";

export class Redirect extends Component {
  constructor( props ){
    super();
    this.state = { ...props };
  }
  componentWillMount(){
    window.location = this.state.route.loc;
  }
  render(){
    return (<section>Redirecting...</section>);
  }
}

export default Redirect;

Context

Stack Overflow Q#42914666, score: 53

Revisions (0)

No revisions yet.