1

I am looking for a solution to render React content conditionally based off the user's Operating System.

Eg. I have a simple component that displays keyboard shortcuts to interact with another component I'm using. In this case, the keyboard shortcuts for Windows and Linux are meant to show ctrl + [action]. But for MacOS it needs to show cmd + [action].

Here's my component:

import React from 'react';

import { ShortcutsContainer, MetaRow } from '../../styles';

const Shortcuts = () => (
  <ShortcutsContainer>
    <h1>Keyboard Shortcuts</h1>
    <MetaRow>
      <strong>ctrl + click</strong>
      <span> to start editing value</span>
    </MetaRow>
    <MetaRow>
      <strong>ctrl + Enter</strong>
      <span> to submit changes</span>
    </MetaRow>
    <MetaRow>
      <strong>Escape</strong>
      <span> to cancel editing</span>
    </MetaRow>
  </ShortcutsContainer>
);

export default Shortcuts;

Let's take <strong>ctrl + click</strong> from that.

What I want is to have something like this:

<strong>{getUserOS() === 'MacOS' ? 'cmd' : 'ctrl'} + click</strong>

How would I accomplish that? Been struggling to find a way to get the user's OS.

Barry Michael Doyle
  • 6,372
  • 18
  • 63
  • 110

4 Answers4

3

Alright, so thanks to @MiguelCalderón recommending I go check the vanilla JS Solution. I check it out and got a solution that works for this use case.

I've created this simple little function:

const cmdOrCtrl = () => (window.navigator.platform.match(/^Mac/) ? 'cmd' : 'ctrl');

And then just implemented it as follows:

<strong>{cmdOrCtrl()} + click</strong>
Barry Michael Doyle
  • 6,372
  • 18
  • 63
  • 110
2
window.navigator.platform

returns for which platform the browser is compiled

ramki
  • 401
  • 3
  • 7
1

May be we can use Platform module to do that.

Just var platform = require('platform'); it and use platform.os to get the OS.

G_S
  • 6,484
  • 2
  • 17
  • 46
1

If i get your question correctly, you are interesting in knowing the operating system of user. You can use something like this

getUserOs= () =>{
 return window.navigator.platform;
} 
SaiKD
  • 62
  • 8