Virtual keyboard interface on a touchscreen with user's hands and a maine coon cat nearby

Typing Made Easy: Unleash the Power of react-simple-keyboard

The Orange Cat
The Orange Cat

In the ever-evolving landscape of web development, creating intuitive and accessible user interfaces remains a top priority. Enter react-simple-keyboard, a powerful and flexible virtual keyboard component designed specifically for React applications. This library offers developers a robust solution for implementing customizable on-screen keyboards, enhancing user input experiences across various devices and platforms.

Features

react-simple-keyboard comes packed with an array of features that make it a standout choice for developers:

  • Customizable layouts: Easily create and switch between different keyboard layouts, including language-specific options.
  • Responsive design: Adapts seamlessly to different screen sizes and orientations.
  • Theme support: Customize the look and feel of the keyboard to match your application’s design.
  • Multi-language support: Implement keyboards for various languages and character sets.
  • Special key handling: Built-in support for special keys like shift, caps lock, and function keys.
  • Input masking: Apply input masks for formatted data entry.
  • Event handling: Rich set of events for precise control over keyboard behavior.
  • Accessibility features: Enhance usability for users relying on assistive technologies.

Installation

To get started with react-simple-keyboard, you can install it via npm or yarn:

npm install react-simple-keyboard

or

yarn add react-simple-keyboard

Basic Usage

Let’s dive into some basic examples to demonstrate how easy it is to integrate react-simple-keyboard into your React application.

Simple Keyboard Component

Here’s a minimal example of how to use the Keyboard component:

import React, { useState } from 'react';
import Keyboard from 'react-simple-keyboard';
import 'react-simple-keyboard/build/css/index.css';

const App: React.FC = () => {
  const [input, setInput] = useState('');

  const onChange = (input: string) => {
    setInput(input);
    console.log('Input changed', input);
  };

  const onKeyPress = (button: string) => {
    console.log('Button pressed', button);
  };

  return (
    <div>
      <input
        value={input}
        placeholder="Tap on the virtual keyboard to start"
        readOnly
      />
      <Keyboard
        onChange={onChange}
        onKeyPress={onKeyPress}
      />
    </div>
  );
};

export default App;

In this example, we import the Keyboard component and its default CSS. We set up a simple state to track the input and define two callback functions: onChange to update the input state, and onKeyPress to log button presses. The keyboard is rendered below an input field, which displays the current input value.

Customizing Keyboard Layout

react-simple-keyboard allows you to easily customize the keyboard layout:

import React, { useState } from 'react';
import Keyboard from 'react-simple-keyboard';
import 'react-simple-keyboard/build/css/index.css';

const App: React.FC = () => {
  const [layoutName, setLayoutName] = useState('default');

  const onChange = (input: string) => {
    console.log('Input changed', input);
  };

  const onKeyPress = (button: string) => {
    console.log('Button pressed', button);
    if (button === '{shift}' || button === '{lock}') {
      setLayoutName(layoutName === 'default' ? 'shift' : 'default');
    }
  };

  const layout = {
    default: [
      '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
      '{tab} q w e r t y u i o p [ ] \\',
      '{lock} a s d f g h j k l ; \' {enter}',
      '{shift} z x c v b n m , . / {shift}',
      '.com @ {space}'
    ],
    shift: [
      '~ ! @ # $ % ^ & * ( ) _ + {bksp}',
      '{tab} Q W E R T Y U I O P { } |',
      '{lock} A S D F G H J K L : " {enter}',
      '{shift} Z X C V B N M < > ? {shift}',
      '.com @ {space}'
    ]
  };

  return (
    <div>
      <Keyboard
        layoutName={layoutName}
        layout={layout}
        onChange={onChange}
        onKeyPress={onKeyPress}
      />
    </div>
  );
};

export default App;

This example demonstrates how to create a custom layout with a shift key that toggles between lowercase and uppercase layouts. The layout prop accepts an object with different layout configurations, and the layoutName prop determines which layout is currently active.

Advanced Usage

Now let’s explore some more advanced features of react-simple-keyboard.

Multi-language Support

Implementing multi-language support is straightforward with react-simple-keyboard:

import React, { useState } from 'react';
import Keyboard from 'react-simple-keyboard';
import 'react-simple-keyboard/build/css/index.css';

const App: React.FC = () => {
  const [language, setLanguage] = useState('english');

  const onChange = (input: string) => {
    console.log('Input changed', input);
  };

  const onKeyPress = (button: string) => {
    console.log('Button pressed', button);
  };

  const layouts = {
    english: {
      default: [
        'q w e r t y u i o p',
        'a s d f g h j k l',
        'z x c v b n m',
        '{space}'
      ]
    },
    russian: {
      default: [
        'й ц у к е н г ш щ з х ъ',
        'ф ы в а п р о л д ж э',
        'я ч с м и т ь б ю',
        '{space}'
      ]
    }
  };

  return (
    <div>
      <select onChange={(e) => setLanguage(e.target.value)}>
        <option value="english">English</option>
        <option value="russian">Russian</option>
      </select>
      <Keyboard
        layout={layouts[language]}
        onChange={onChange}
        onKeyPress={onKeyPress}
      />
    </div>
  );
};

export default App;

This example shows how to switch between English and Russian keyboard layouts. You can easily extend this to support more languages by adding more layout configurations.

Input Masking

react-simple-keyboard supports input masking for formatted data entry. Here’s an example of implementing a simple phone number mask:

import React, { useState } from 'react';
import Keyboard from 'react-simple-keyboard';
import 'react-simple-keyboard/build/css/index.css';

const App: React.FC = () => {
  const [input, setInput] = useState('');

  const onChange = (input: string) => {
    const formattedInput = formatPhoneNumber(input);
    setInput(formattedInput);
  };

  const formatPhoneNumber = (value: string) => {
    const phoneNumber = value.replace(/[^\d]/g, '');
    const phoneNumberLength = phoneNumber.length;
    if (phoneNumberLength < 4) return phoneNumber;
    if (phoneNumberLength < 7) {
      return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
    }
    return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
      3,
      6
    )}-${phoneNumber.slice(6, 10)}`;
  };

  return (
    <div>
      <input
        value={input}
        placeholder="(123) 456-7890"
        readOnly
      />
      <Keyboard
        onChange={onChange}
        layout={{
          default: ['1 2 3', '4 5 6', '7 8 9', '{bksp} 0 {enter}']
        }}
      />
    </div>
  );
};

export default App;

This example demonstrates how to implement a phone number input mask. The formatPhoneNumber function formats the input as it’s entered, providing immediate visual feedback to the user.

Theme Customization

react-simple-keyboard allows for extensive theme customization. Here’s an example of how to apply a custom theme:

import React from 'react';
import Keyboard from 'react-simple-keyboard';
import 'react-simple-keyboard/build/css/index.css';

const App: React.FC = () => {
  const onChange = (input: string) => {
    console.log('Input changed', input);
  };

  const customTheme = {
    buttonTheme: [
      {
        class: "hg-red",
        buttons: "Q W E R T Y"
      },
      {
        class: "hg-highlight",
        buttons: "A S D F G H"
      }
    ]
  };

  const customButtonTheme = {
    'hg-red': {
      backgroundColor: 'red',
      color: 'white'
    },
    'hg-highlight': {
      backgroundColor: 'yellow',
      color: 'black'
    }
  };

  return (
    <div>
      <Keyboard
        onChange={onChange}
        buttonTheme={customTheme.buttonTheme}
        theme={'hg-theme-default hg-layout-default custom-keyboard'}
      />
      <style>
        {`
          .custom-keyboard {
            max-width: 850px;
          }
          .custom-keyboard .hg-button {
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: rgba(0, 0, 0, 0.5);
            color: white;
          }
          ${Object.entries(customButtonTheme).map(([className, styles]) => `
            .custom-keyboard .${className} {
              ${Object.entries(styles).map(([prop, value]) => `${prop}: ${value};`).join('\n')}
            }
          `).join('\n')}
        `}
      </style>
    </div>
  );
};

export default App;

This example showcases how to apply custom themes to specific buttons and override the default styles. The buttonTheme prop allows you to assign classes to specific buttons, while the inline <style> tag defines the custom CSS for these classes.

Conclusion

react-simple-keyboard is a powerful and flexible library that brings the convenience of virtual keyboards to React applications. Its extensive customization options, multi-language support, and advanced features like input masking make it an excellent choice for developers looking to enhance user input experiences.

Whether you’re building a touch-friendly web application, a kiosk interface, or simply want to provide an alternative input method, react-simple-keyboard offers a robust solution. By leveraging its features and customization options, you can create intuitive and accessible interfaces that cater to a wide range of user needs and preferences.

As you continue to explore react-simple-keyboard, you’ll discover even more ways to tailor the keyboard to your specific requirements, ensuring a seamless and user-friendly input experience in your React applications.

Comments