All posts

How to set state from a URL using React

 react

During the development of a view for an oAuth application I wanted to reuse an existing login screen and session create functionality but add some new logic based on if the login screen was for the oAuth workflow or standard user login.

To accomplish this I chose to set state based on the url because the oauth url contained the path /oauth and then I could base other checks around that state.

I needed to set this state before render so I added it to the constructor of a class based component. The result looked like this:

constructor(props) {
  super(props);

  const oauthProviderFlow = (window.location.pathname.includes("oauth") ? true : false);
  this.state = {oauthApp: null, oauthProviderFlow: oauthProviderFlow};  
}

Above I check that the url path contains the substring “oauth” and update the state to true if that is the case. Then I will have that state available for the first render and beyond (you’re welcome for now thinking of Buzz).