Search code examples
reactjsoperating-systemconditional-rendering

How to conditionally render ReactJS content based of user's Operation System


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.


Solution

  • 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>