0

Do you have a better way to create this if / elseif sentence?

 if ((navigator.userAgent.indexOf('Opera') || navigator.userAgent.indexOf('OPR')) != -1) {
      this.state.isBrowserAllowed = true;
    } else if (navigator.userAgent.indexOf('Chrome') != -1) {
      this.state.isBrowserAllowed = true;
    } else if (navigator.userAgent.indexOf('Safari') != -1) {
      this.state.isBrowserAllowed = true;
    } else if (navigator.userAgent.indexOf('Firefox') != -1) {
      this.state.isBrowserAllowed = true;
    }

5
  • You should not mutate the state directly. Use this.setState Commented Oct 17, 2020 at 16:27
  • Do you actually need to block other browsers (assuming that's what you're doing)? Commented Oct 17, 2020 at 16:29
  • This is not a duplicate of "Check variable equality against a list of values" - the userAgent is a long string which may contain certain browser substrings Commented Oct 17, 2020 at 16:30
  • Yes I'm trying to detect when user try to use my web on Instagram or Xiomi, or other browser... Commented Oct 17, 2020 at 16:31
  • looks like a duplicate of stackoverflow.com/questions/13737091/… Commented Oct 17, 2020 at 16:54

1 Answer 1

4

I'd use a regular expression instead.

this.setState({
  ...this.state,
  isBrowserAllowed: /Opera|OPR|Chrome|Safari|Firefox/.test(navigator.userAgent)
});

Also, as the comment notes, state should not be mutated in React - use setState instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.